package cn.stylefeng.guns.modular.order.service.impl;

import java.io.InputStream;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.modular.order.service.*;
import cn.stylefeng.guns.modular.replenishment.service.ReplenishmentOrderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.ExcelWrite;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicGoods;
import cn.stylefeng.guns.modular.basic.entity.BasicTray;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPositionParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicTrayParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicWarehouseParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicAddressResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicOperateResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPositionResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicPutgoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicTrayResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicWarehouseResult;
import cn.stylefeng.guns.modular.basic.service.BasicAddressService;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicOperateService;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicPrivatecarService;
import cn.stylefeng.guns.modular.basic.service.BasicPutgoodsService;
import cn.stylefeng.guns.modular.basic.service.BasicTrayService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.order.entity.OrderTransport;
import cn.stylefeng.guns.modular.order.entity.OutOrder;
import cn.stylefeng.guns.modular.order.entity.OutOrderExcelItem;
import cn.stylefeng.guns.modular.order.entity.OutOrderExcelQlItem;
import cn.stylefeng.guns.modular.order.mapper.OutOrderMapper;
import cn.stylefeng.guns.modular.order.model.params.DealWithParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderResult;
import cn.stylefeng.guns.modular.storage.entity.StorageOutDetailed;
import cn.stylefeng.guns.modular.storage.entity.StorageStock;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutDetailedParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.params.StorageStockParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutDetailedResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutResult;
import cn.stylefeng.guns.modular.storage.model.result.StorageStockResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.modular.storage.service.StoragePutService;
import cn.stylefeng.guns.modular.storage.service.StoragePutSingleService;
import cn.stylefeng.guns.modular.storage.service.StorageStockDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageStockService;
import cn.stylefeng.guns.modular.tool.model.params.ToolStorageStockParam;
import cn.stylefeng.guns.modular.tool.model.result.ToolStorageStockResult;
import cn.stylefeng.guns.modular.tool.service.ToolStorageStockService;
import cn.stylefeng.guns.modular.transport.model.params.TransportDispatchParam;
import cn.stylefeng.guns.modular.transport.model.result.TransportDispatchResult;
import cn.stylefeng.guns.modular.transport.service.TDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportDispatchService;
import cn.stylefeng.guns.modular.transport.service.TransportReceiptService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 出库订单表 服务实现类
 */
@Service
public class OutOrderServiceImpl extends ServiceImpl<OutOrderMapper, OutOrder> implements OutOrderService {

    @Resource
    private TransportReceiptService transportReceiptService;
    @Resource
    private BasicCustomerService basicCustomerService;

    @Resource
    private BasicWarehouseService basicWarehouseService;
    
    @Resource
    private BasicPutgoodsService basicPutgoodsService;

    @Resource
    private UserService userService;
    
    @Resource
    private BasicAddressService basicAddressService;

    @Resource
    private OrderTransportService orderTransportService;

    @Resource
    private BasicOperateService basicOperateService;

    @Resource
    private BasicGoodsService basicGoodsService;
    
    @Resource
    private OutOrderDetailedService outOrderDetailedService;

    @Resource
    private StorageOutService storageOutService;

    @Resource
    private StorageOutDetailedService storageOutDetailedService;

    @Resource
    private OrderPutService orderPutService;

    @Resource
    private OrderPutDetailedService orderPutDetailedService;

    @Resource
    private StoragePutService storagePutService;

    @Resource
    private StoragePutSingleService storagePutSingleService;

    @Resource
    private StorageStockService storageStockService;

    @Resource
    private BasicPositionService basicPositionService;

    @Resource
    private BasicTrayService basicTrayService;

    @Resource
    private OrderTransportDetailedService orderTransportDetailedService;

	@Resource
    private TransportDispatchService transportDispatchService;

    @Resource
    private BasicPrivatecarService basicPrivatecarService;

    @Resource
    private TDispatchService tDispatchService;
    @Resource
    private ToolStorageStockService toolStorageStockService;
	@Autowired
	private OutOrderService outOrderService;
	@Autowired
	private BasicGoodsService goodsService;
	@Autowired
	ReplenishmentOrderService replenishmentOrderService; // 补货
	@Autowired
	JSTOutOrderScheduledService jstOutOrderScheduledService; // 定时任务

    @Override
    public void add(OutOrderParam param){
        OutOrder entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(OutOrderParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(OutOrderParam param){
        OutOrder oldEntity = getOldEntity(param);
        OutOrder newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public OutOrderResult findBySpec(OutOrderParam param,Long operateId){
        return this.baseMapper.findBySpec(param, operateId);
    }

    @Override
    public List<OutOrderResult> findListBySpec(OutOrderParam param, Long operateId){
        return this.baseMapper.findListBySpec(param,operateId);
    }

    @Override
    public LayuiPageInfo findPageBySpec(OutOrderParam param,String condition, Long operateId){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
    }

	@Override
	public List<OutOrderResult> dtjOrderNumberList(OutOrderParam param, Long operateId) {
		return this.baseMapper.dtjOrderNumberList(param,operateId);
	}

	@Override
    public OutOrder findByTheLastOne() {
        return this.baseMapper.findByTheLastOne();
    }

    private Serializable getKey(OutOrderParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private OutOrder getOldEntity(OutOrderParam param) {
        return this.getById(getKey(param));
    }

    private OutOrder getEntity(OutOrderParam param) {
        OutOrder entity = new OutOrder();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 处理出库导入数据
     */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData excelAdd(List<OutOrderExcelItem> putExcelList, OutOrderParam outOrderParam, ResponseData data) {
		if(outOrderParam.getOutCustomerId()==null||outOrderParam.getTransportWay()==null||outOrderParam.getSettlementWay()==null) {
			data.setSuccess(false);
				data.setMessage("Please fill in order basic information!");
				return data;
		}
		List<OutOrderParam> outorderList = new ArrayList<OutOrderParam>();//批量保存的 出库订单list
		List<OrderTransportParam> transportList = new ArrayList<OrderTransportParam>();//批量保存的 货运订单list
		List<OutOrderDetailedParam> detailedList = new ArrayList<OutOrderDetailedParam>();//批量保存的 出库订单明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(outOrderParam.getOutCustomerId());//客户信息
		User user = userService.getcurrentUser();
		Long DeptId = user.getDeptId();
		Long DeliverId = user.getDeliverId();
		String name = user.getName();

		//查询最新 出库订单
    	OutOrder outOrder = this.findByTheLastOne();
    	int outOrderNumber = 1;
        if (outOrder != null){
        	outOrderNumber = outOrder.getId()+1;
        }
        DealWithParam dealWithParam = new DealWithParam();
        dealWithParam.setNewCustomersflag(false);
        //查询最新 货运订单
    	OrderTransport t = orderTransportService.findByThelastone();
    	int transportNumber = 1;
    	if (t!=null) {
    		transportNumber = t.getId()+1;
		} 
		for (OutOrderExcelItem ExcelItem : putExcelList) {
			if(ExcelItem.getWarehouseNumber()==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse number cannot be empty in imported data!");
				return data;
			}
			BasicWarehouseParam bawp = new BasicWarehouseParam();
			bawp.setWarehouseNumber(ExcelItem.getWarehouseNumber());
			bawp.setDeliverId(DeliverId);
			BasicWarehouseResult bawr = basicWarehouseService.findBySpec(bawp,DeptId,user.getOperateId() );//仓库信息
			if(bawr==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse does not exist in imported data!");
				return data;
			}
			if(ExcelItem.getCustomerNumber()==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Customer order number cannot be empty in imported data!");
				return data;
			}
			if(ExcelItem.getGetUnitName()==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Consignee customer cannot be empty in imported data!");
				return data;
			}
			if(ExcelItem.getGoodsNumber()==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Product number cannot be empty in imported data!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			OutOrderParam oop = new OutOrderParam();
			oop.setCustomerNumber(ExcelItem.getCustomerNumber());//导入数据 (客户单号)
			OutOrderResult oorOrderResult = this.findBySpec(oop,null);
			//如果不存在
			if (oorOrderResult==null) {
				//新增出库订单
				OutOrderParam oodp = new OutOrderParam();
	        	oodp.setOutOrderNumber("ORDER-CK"+outOrderNumber);//系统单号
				oodp.setOutOrderStatus("PENDING_SUBMIT");//单据状态
		        oodp.setOutCustomerId(outOrderParam.getOutCustomerId());//所属客户id
		        oodp.setOutCustomerName(basicCustomer.getCustomerName());//所属客户名称
		        oodp.setCustomerNumber(ExcelItem.getCustomerNumber());//客户单号 (Excel导入数据中 客户单号)
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		        try {
					Date date = sdf.parse(getDatesssss());
			        oodp.setOutTime(date);
				} catch (Exception e) {
					e.printStackTrace();
				}
		        oodp.setOutWay("Self Pickup");// 窗口接货生成  上门提货不生成
		        oodp.setOutStorehouseId(Long.parseLong(bawr.getId().toString()));//仓库id
		        oodp.setStorehouseName(bawr.getWarehouseName());//仓库名称
		        oodp.setSettlementWay(outOrderParam.getSettlementWay());//结算方式
		        oodp.setTransportWay(outOrderParam.getTransportWay());//运输方式
		        oodp.setCarNumber(ExcelItem.getCarNumber());//车牌号 (Excel导入数据中 车号)
		        toDealWith(oodp,basicCustomer,ExcelItem,dealWithParam);//处理单位和地址
		        
		        try {
					 Date time = new Date(ExcelItem.getConsignmentdate());
			         String timeFormat = sdf.format(time);
			         oodp.setSetMentiontime(timeFormat);//发货日期
				} catch (Exception e) {
					// TODO: handle exception
				}
				oodp.setNote(ExcelItem.getNodes());//备注
		        oodp.setDeptId(DeptId);
		        oodp.setDeliverId(DeliverId);
		        oodp.setCreateUserName(name);
		        oodp.setFactoryNumber(ExcelItem.getFactory());//工厂编号
		        oodp.setFactoryName(ExcelItem.getFactoryName());//工厂名称
		        oodp.setTurnNumber(ExcelItem.getTurnNumber());//转储编号
		        oodp.setTransportNumber(ExcelItem.getTransportNumber());//货运编号
		        oodp.setProcurementNumber(ExcelItem.getPurchaserNumber());//客户采购订单编号
		    	boolean whether = false;//判断客户单号  是否重复
		    	for (OutOrderParam opp2 : outorderList) {
					if (opp2.getCustomerNumber().equals(oodp.getCustomerNumber())) {
						whether = true;
						oorOrderResult = new OutOrderResult();
		    			ToolUtil.copyProperties(opp2,oorOrderResult);
					}
				}
		    	if (!whether) {
		    		outorderList.add(oodp);
		    		outOrderNumber++;
					oorOrderResult = new OutOrderResult();
	    			ToolUtil.copyProperties(oodp,oorOrderResult);
				}
		    	oodp = new OutOrderParam();
			}
			//如果 导入的客户单号 已存在，并且状态不等于 待提交
			if (!"PENDING_SUBMIT".equals(oorOrderResult.getOutOrderStatus())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Customer order number already exists in imported data! "+oorOrderResult.getCustomerNumber());
				return data;
			}
			boolean hy = true;//true 生成  false不生成
			if (hy) {
				//生成货运订单
				OrderTransportParam otp = new OrderTransportParam();
		    	otp.setCustomerOrder(oorOrderResult.getCustomerNumber());//客户单号
				OrderTransportResult otr = orderTransportService.findBySpec(otp,null);
				if (otr==null) {
					List<BasicOperateResult> oList =  basicOperateService.findAvailableList(DeptId,DeliverId,user.getOperateId());
					if (oList.size()>0) {
						otp.setOperateId(Long.parseLong(oList.get(0).getId().toString()));//分公司id
						otp.setOperateName(oList.get(0).getOperateName());//公司名称
					}
		    		otp.setTransportNumber("ORDER-TY-"+transportNumber);//货运单号
			    	otp.setCustomerId(Long.parseLong(basicCustomer.getId().toString()));//客户id
			    	otp.setCustomerName(basicCustomer.getCustomerName());//客户名称
			    	otp.setUndertime(getDatesssss());//下单时间
					otp.setOrderNumber(oorOrderResult.getOutOrderNumber());//订单号
			    	otp.setTstate("h");//状态为h
			    	otp.setSetUnit(oorOrderResult.getSetUnit());//装货单位
			    	otp.setSetUnitId(oorOrderResult.getSetUnitId());//装货单位id
			    	otp.setSetLocation(oorOrderResult.getSetLocation());//装货地点
			    	otp.setSetLocationId(oorOrderResult.getSetLocationId());//装货地点id
			    	otp.setSetPeople(oorOrderResult.getSetPeople());//联系人
			    	otp.setSetTel(oorOrderResult.getSetTel());//联系电话
			    	otp.setSetMentiontime(getDatesssss());//提货时间
					otp.setNodes(oorOrderResult.getNote());//备注
			    	otp.setDeptId(DeptId);
			    	otp.setDeliverId(DeliverId);
			    	
			    	otp.setGetUnit(oorOrderResult.getGetUnit());//卸货单位
			    	otp.setGetUnitId(oorOrderResult.getGetUnitId());//卸货单位id
			    	otp.setGetLocation(oorOrderResult.getGetLocation());//卸货地点
			    	otp.setGetLocationId(oorOrderResult.getGetLocationId());//卸货地点id
			    	otp.setGetPeople(oorOrderResult.getGetPeople());//联系人
			    	otp.setGetTel(oorOrderResult.getGetTel());//联系电话
			    	
			    	otp.setCreateName(name);
			    	otp.setCreateTime(new Date());
			    	otp.setCreateUser(userService.getcurrentUser().getUserId());
			    	boolean whether = false;//判断客户单号  是否重复
			    	for (OrderTransportParam orp2 : transportList) {
						if (orp2.getCustomerOrder().equals(otp.getCustomerOrder())) {
							whether = true;
						}
					}
			    	if (!whether) {
			    		transportList.add(otp);
			    		transportNumber++;
					}
			    	otp = new OrderTransportParam();
			    	otr = new OrderTransportResult();
				} else {
					//如果 导入的客户单号 已存在，并且订单状态不等于待提交
					if(!"PENDING_SUBMIT".equals(otr.getTstate())) {
		                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
						data.setSuccess(false);
						data.setMessage("Customer transport order number already exists in imported data!");
						return data;
					}
				}
			}
			
			//判断商品是否存在
			BasicGoodsParam bgp = new BasicGoodsParam();
			bgp.setGoodsNumber(ExcelItem.getGoodsNumber());
			bgp.setDeliverId(DeliverId);
			bgp.setDeptId(DeptId);
			BasicGoodsResult bgr = basicGoodsService.findBySpec(bgp,user.getOperateId());
			if (bgr==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Product does not exist in imported data! Number: "+ExcelItem.getGoodsNumber());
				return data;
			}
			//计算 单价，体积单位
			BigDecimal outnum = new BigDecimal(ExcelItem.getBignum());//应出数量
			BigDecimal outvolume =  new BigDecimal(ExcelItem.getOutVolume());//应入体积
			BigDecimal outMoney = new BigDecimal(ExcelItem.getPrice());//金额
			BigDecimal as = new BigDecimal(0);
			BigDecimal v = as;//体积单位
			if(bgr.getGoodsVolume()!=null){
				v = new BigDecimal(bgr.getGoodsVolume());//体积单位
			}
			BigDecimal u = as;//计费指定价
			if(bgr.getGoodsCharging()!=null){
				u = new BigDecimal(bgr.getGoodsCharging());
			}
			BigDecimal w = as;//重量单位
			if(bgr.getGoodsWeight()!=null){
				w = new BigDecimal(bgr.getGoodsWeight());//重量单位
			}
			if (outvolume.compareTo(as)==1) {//大于 返回1 
				v = outvolume.divide(outnum,6,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留6位)
				bgr.setGoodsVolume(v.toString());//最新体积单位
			}
			if(outMoney.compareTo(as)==1) {//大于 返回1 
				u = outMoney.divide(outnum,6,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留6位)
				bgr.setGoodsCharging(u.toString());//最新 计费指定价
			}
			//更新最新体积单位，计费指定价
			ToolUtil.copyProperties(bgr,bgp);
			basicGoodsService.update(bgp);
			//生成出库订单明细
			String batch = ExcelItem.getBatch();//导入生产日期 1905260728  = 日期190526+编号0728
			String detailedDate = null;
			if (batch!=null&&batch!="") {
				detailedDate = "20"+batch.substring(0, 6);//切割日期
			}
			StringBuffer strBuffer = new StringBuffer();
			if (detailedDate!=null) {
				char[] dataArray = detailedDate.toCharArray();
				for(int i = 0; i < dataArray.length; i++){
				strBuffer.append(dataArray[i]);
					if(i == 3 || i == 5){
					strBuffer.append("-");
					}
				}
			}
			
			OutOrderDetailedParam oodp = new OutOrderDetailedParam();
			oodp.setDetailedFactory(ExcelItem.getFactory());//工厂号
			oodp.setDetailedOutNumber(oorOrderResult.getOutOrderNumber());//出库订单编号
			oodp.setDetailedGoodscode(bgp.getGoodsNumber());//商品编号
			oodp.setDetailedGoodsId(Long.parseLong(bgp.getId().toString()));//商品id
			oodp.setDetailedGoodsname(bgp.getGoodsName());//商品名称
			oodp.setDetailedPutbalenum(outnum.toString());//大包数量
			oodp.setDetailedNumber(outnum.toString());//数量
			oodp.setDetailedWeight(w.toString());//重量
			oodp.setDetailedOutWeight(w.multiply(outnum).toString());//应出重量
			oodp.setDetailedVolume(v.toString());//体积
			oodp.setDetailedOutVolume(v.multiply(outnum).toString());//应出体积
			oodp.setDetailedPrice(u.toString());//单价
			oodp.setDetailedMoney(u.multiply(outnum).toString());//金额
			if (detailedDate!=null) {
				oodp.setDetailedBatchnumber(detailedDate);//批次号
				oodp.setDetailedDate(strBuffer.toString());//生产日期
			}
			oodp.setDetailedRebubbles(bgr.getGoodsHeavybubble());//重泡货
			oodp.setDetailedPacking(bgr.getGoodsPacking());//商品包装
			oodp.setDetailedLargeclass(bgr.getGoodsBigtype());//商品大类
			oodp.setDetailedGoodstype(bgr.getGoodsType());//商品类别
			oodp.setDetailedPutcondition(bgr.getGoodsCondition());//保管条件
			oodp.setCreateTime(new Date());
			oodp.setCreateUser(userService.getcurrentUser().getUserId());
			detailedList.add(oodp);
			oodp = new OutOrderDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(outorderList);
			orderTransportService.saveBatchList(transportList);
			outOrderDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		if (dealWithParam.isNewCustomersflag()) {
			data.setCode(450);
			data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", "")+"Please promptly maintain the route and correct the address for the new unit! To avoid affecting vehicle dispatching and driver delivery.");
		}
        return data;
	}

    @Override
    public OutOrderResult findbyoutOrderNumber(String outOrderNumber) {
		return this.baseMapper.findbyoutOrderNumber(outOrderNumber);
    }

	@Override
	public OutOrderResult findbyoutOrderNumberByDeptId(String customerNumber, String outOrderNumber, Long deptId) {
		return this.baseMapper.findbyoutOrderNumberByDeptId(customerNumber, outOrderNumber, deptId);
	}

	//处理单位地址
	private void toDealWithQl(OutOrderParam oodp, BasicCustomer basicCustomer, OutOrderExcelQlItem ExcelItem,DealWithParam dealWithParam) {
        User user = userService.getcurrentUser();
        //查询装货单位 是否存在
        BasicPutgoodsParam bpgp = new BasicPutgoodsParam();
        bpgp.setPutgoodsCustomerId(basicCustomer.getId());//客户id
        bpgp.setPutgoodsName(ExcelItem.getFahuocangku());//单位名称
        BasicPutgoodsResult bputr = basicPutgoodsService.findBySpec(bpgp,null);
        if (bputr==null) {
        	bpgp.setPutgoodsOperateName(basicCustomer.getCustomerName());//客户名称
        	bpgp.setDeliverId(user.getDeliverId());
        	bpgp.setDeptId(user.getDeptId());
        	basicPutgoodsService.add(bpgp);
        	dealWithParam.setNewCustomersflag(true);
        	dealWithParam.setNewCustomers(dealWithParam.getNewCustomers()+"New Pickup Unit："+ExcelItem.getFahuocangku()+"；");
	        BasicPutgoodsParam bpgp2 = new BasicPutgoodsParam();
	        bpgp2.setPutgoodsCustomerId(basicCustomer.getId());//客户id
	        bpgp2.setPutgoodsName(ExcelItem.getFahuocangku());//单位名称
	        bputr = basicPutgoodsService.findBySpec(bpgp2,null);
		}
        oodp.setSetUnit(bputr.getPutgoodsName());//装货单位
        oodp.setSetUnitId(Long.parseLong(bputr.getId().toString()));//装货单位id
        //查询装货地点 是否存在
        BasicAddressParam bap = new BasicAddressParam();
        bap.setPutgoodsId(Long.parseLong(bputr.getId().toString()));//单位id
        BasicAddressResult bar = basicAddressService.findBySpec(bap);//通过单位id 地址 查询
        if (bar != null){
			oodp.setSetLocation(bar.getAddress());//装货地址
			oodp.setSetLocationId(Long.parseLong(bar.getId().toString()));//装货地址id
			oodp.setSetPeople(bar.getContacts());//联系人
			oodp.setSetTel(bar.getTel());//联系电话
		} else {
			BasicWarehouseParam basicWarehouseParam = new BasicWarehouseParam();
			basicWarehouseParam.setWarehouseName(ExcelItem.getFahuocangku());
			BasicWarehouseResult basicWarehouseResult = basicWarehouseService.findBySpec(basicWarehouseParam, user.getDeptId(),user.getOperateId());
			if(basicWarehouseResult != null) {
				bap.setAddress(basicWarehouseResult.getWarehouseAddress());
				bap.setTel(basicWarehouseResult.getTel());
				bap.setContacts(basicWarehouseResult.getWarehouseContacts());
			} else {
	        	bap.setAddress(bputr.getPutgoodsName());//地点 为单位名称
				bap.setTel(bputr.getPutgoodsTel());//联系电话 (单位 的联系电话)
				bap.setContacts(bputr.getPutgoodsContacts());
			}
			
			bap.setPutgoodsName(bputr.getPutgoodsName());//单位名称
			bap.setSwitchWl("1");
			bap.setSwitchBj("1500");//提货围栏半径 默认100米
			bap.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap);
	        BasicAddressParam bap2 = new BasicAddressParam();
	        bap2.setPutgoodsId(Long.parseLong(bputr.getId().toString()));
        	bar = basicAddressService.findBySpec(bap2);
			oodp.setSetLocation(bar.getAddress());//装货地址
			oodp.setSetLocationId(Long.parseLong(bar.getId().toString()));//装货地址id
			oodp.setSetPeople(bar.getContacts());//联系人
			oodp.setSetTel(bar.getTel());//联系电话
		} 

        //查询卸货单位 是否存在
        BasicPutgoodsParam bpgp3 = new BasicPutgoodsParam();
        bpgp3.setPutgoodsCustomerId(basicCustomer.getId());//客户id
        bpgp3.setPutgoodsName(ExcelItem.getShouhuokehu());//单位名称  (Excel导入数据中 的收货客户)
        BasicPutgoodsResult bputr2 = basicPutgoodsService.findBySpec(bpgp3,null);
        if (bputr2==null) {
        	bpgp3.setPutgoodsOperateName(basicCustomer.getCustomerName());//客户名称
        	bpgp3.setDeliverId(userService.getDeliverId());
        	bpgp3.setDeptId(userService.getDeptId());
        	bpgp3.setUnitNumber(ExcelItem.getKehubianhao());//单位编号(Excel导入数据中 的客户编号)
        	bpgp3.setPutgoodsContacts(ExcelItem.getShouhuoren());
        	basicPutgoodsService.add(bpgp3);
        	dealWithParam.setNewCustomersflag(true);
        	dealWithParam.setNewCustomers(dealWithParam.getNewCustomers()+"New Consignee Unit："+ExcelItem.getShouhuokehu()+"；");
	        BasicPutgoodsParam bpgp4 = new BasicPutgoodsParam();
	        bpgp4.setPutgoodsCustomerId(basicCustomer.getId());//客户id
	        bpgp4.setPutgoodsName(ExcelItem.getShouhuokehu());//单位名称
	        bputr2 = basicPutgoodsService.findBySpec(bpgp4,null);
		}
        oodp.setGetUnit(bputr2.getPutgoodsName());//卸货单位
        oodp.setGetUnitId(Long.parseLong(bputr2.getId().toString()));//卸货单位id
        //查询卸货地点 是否存在
        BasicAddressParam bap3 = new BasicAddressParam();
        bap3.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));//单位id
        BasicAddressResult bar2 = basicAddressService.findBySpec(bap3);//通过单位id 地址 查询
        if(bar2 != null) {
			oodp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
        	if(ToolUtil.isNotEmpty(ExcelItem.getKehudizhi())) {
            	bap3.setAddress(ExcelItem.getKehudizhi());
    			oodp.setGetLocation(ExcelItem.getKehudizhi());//卸货地址
        	} else {
        		oodp.setGetLocation(bar2.getAddress());//卸货地址
        	}
        	if(ToolUtil.isNotEmpty(ExcelItem.getShouhuoren())) {
            	bap3.setContacts(ExcelItem.getShouhuoren());
    			oodp.setGetPeople(ExcelItem.getShouhuoren());//联系人
        	} else {
        		oodp.setGetPeople(bar2.getContacts());//联系人
        	}
        	if(ToolUtil.isNotEmpty(ExcelItem.getKehudianhua())) {
            	bap3.setTel(ExcelItem.getKehudianhua());
    			oodp.setGetTel(ExcelItem.getKehudianhua());//联系电话
        	} else {
        		oodp.setGetTel(bar2.getTel());//联系电话
        	}       	
        	bap3.setId(bar2.getId());
        	basicAddressService.update(bap3);
        } else if (bar2==null&&ToolUtil.isEmpty(ExcelItem.getKehudizhi())) {//如果没有地址 并且Excel中收货客户地址 为空，  卸货地址为 单位名称
        	bap3.setAddress(bputr2.getPutgoodsName());//地点 为单位名称
			bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
			bap3.setTel(bputr2.getPutgoodsTel());//联系电话 (单位 的联系电话)
			bap3.setContacts(bputr2.getPutgoodsContacts());
			bap3.setSwitchWl("1");
			bap3.setSwitchBj("1500");//提货围栏半径 默认100米
			bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap3);
	        BasicAddressParam bap4 = new BasicAddressParam();
	        bap4.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));
        	bap4.setAddress(ExcelItem.getKehudizhi());
        	bar2 = basicAddressService.findBySpec(bap4);
			oodp.setGetLocation(bar2.getAddress());//卸货地址
			oodp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
			oodp.setGetPeople(bar2.getContacts());//联系人
			oodp.setGetTel(bar2.getTel());//联系电话
		} else if(bar2==null&&ToolUtil.isNotEmpty(ExcelItem.getKehudizhi())){//如果没有地址  Excel中有收货客户地址  新增基础数据 地址
        	bap3.setAddress(ExcelItem.getKehudizhi());//地点 (Excel中收货客户地址)
			bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
			bap3.setTel(ExcelItem.getKehudianhua());//联系电话 (Excel中的 收货客户电话)
			bap3.setContacts(ExcelItem.getShouhuoren());
			bap3.setSwitchWl("1");
			bap3.setSwitchBj("1500");//提货围栏半径 默认100米
			bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap3);
	        BasicAddressParam bap4 = new BasicAddressParam();
	        bap4.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));
        	bap4.setAddress(ExcelItem.getKehudizhi());
        	bar2 = basicAddressService.findBySpec(bap4);
			oodp.setGetLocation(bar2.getAddress());//卸货地址
			oodp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
			oodp.setGetPeople(bar2.getContacts());//联系人
			oodp.setGetTel(bar2.getTel());//联系电话
		} 
	}

    //处理单位地址
	private void toDealWith(OutOrderParam oodp, BasicCustomer basicCustomer, OutOrderExcelItem ExcelItem,DealWithParam dealWithParam) {
        User user = userService.getcurrentUser();
        //查询装货单位 是否存在
        BasicPutgoodsParam bpgp = new BasicPutgoodsParam();
        bpgp.setPutgoodsCustomerId(basicCustomer.getId());//客户id
        bpgp.setPutgoodsName(ExcelItem.getWarehouseName());//单位名称
        BasicPutgoodsResult bputr = basicPutgoodsService.findBySpec(bpgp,null);
        if (bputr==null) {
        	bpgp.setPutgoodsOperateName(basicCustomer.getCustomerName());//客户名称
        	bpgp.setDeliverId(user.getDeliverId());
        	bpgp.setDeptId(user.getDeptId());
        	basicPutgoodsService.add(bpgp);
        	dealWithParam.setNewCustomersflag(true);
        	dealWithParam.setNewCustomers(dealWithParam.getNewCustomers()+"New Pickup Unit："+ExcelItem.getWarehouseName()+"；");
	        BasicPutgoodsParam bpgp2 = new BasicPutgoodsParam();
	        bpgp2.setPutgoodsCustomerId(basicCustomer.getId());//客户id
	        bpgp2.setPutgoodsName(ExcelItem.getWarehouseName());//单位名称
	        bputr = basicPutgoodsService.findBySpec(bpgp2,null);
		}
        oodp.setSetUnit(bputr.getPutgoodsName());//装货单位
        oodp.setSetUnitId(Long.parseLong(bputr.getId().toString()));//装货单位id
        //查询装货地点 是否存在
        BasicAddressParam bap = new BasicAddressParam();
        bap.setPutgoodsId(Long.parseLong(bputr.getId().toString()));//单位id
        BasicAddressResult bar = basicAddressService.findBySpec(bap);//通过单位id 地址 查询
        if (bar != null){
			oodp.setSetLocation(bar.getAddress());//装货地址
			oodp.setSetLocationId(Long.parseLong(bar.getId().toString()));//装货地址id
			oodp.setSetPeople(bar.getContacts());//联系人
			oodp.setSetTel(bar.getTel());//联系电话
		} else if (bar==null&&ToolUtil.isEmpty(ExcelItem.getSetUnit())) {//如果没有地址 并且Excel中库存地点名称 为空，  装货地址为 单位名称
			BasicWarehouseParam basicWarehouseParam = new BasicWarehouseParam();
			basicWarehouseParam.setWarehouseName(ExcelItem.getWarehouseName());
			BasicWarehouseResult basicWarehouseResult = basicWarehouseService.findBySpec(basicWarehouseParam, user.getDeptId(),user.getOperateId());
			if(basicWarehouseResult != null) {
				bap.setAddress(basicWarehouseResult.getWarehouseAddress());
				bap.setTel(basicWarehouseResult.getTel());
				bap.setContacts(basicWarehouseResult.getWarehouseContacts());
			} else {
	        	bap.setAddress(bputr.getPutgoodsName());//地点 为单位名称
				bap.setTel(bputr.getPutgoodsTel());//联系电话 (单位 的联系电话)
				bap.setContacts(bputr.getPutgoodsContacts());
			}
			
			bap.setPutgoodsName(bputr.getPutgoodsName());//单位名称
			bap.setSwitchWl("1");
			bap.setSwitchBj("1500");//提货围栏半径 默认100米
			bap.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap);
	        BasicAddressParam bap2 = new BasicAddressParam();
	        bap2.setPutgoodsId(Long.parseLong(bputr.getId().toString()));
        	bar = basicAddressService.findBySpec(bap2);
			oodp.setSetLocation(bar.getAddress());//装货地址
			oodp.setSetLocationId(Long.parseLong(bar.getId().toString()));//装货地址id
			oodp.setSetPeople(bar.getContacts());//联系人
			oodp.setSetTel(bar.getTel());//联系电话
		} else if(bar==null&&ToolUtil.isNotEmpty(ExcelItem.getSetUnit())){//如果没有地址  Excel中有库存地点名称  新增基础数据 地址
        	bap.setAddress(ExcelItem.getSetUnit());//地点 (Excel中库存地点名称)
			bap.setPutgoodsName(bputr.getPutgoodsName());//单位名称
			bap.setTel(ExcelItem.getGetUnitTel());//联系电话 (Excel中的 收货客户电话)
			bap.setSwitchWl("1");
			bap.setSwitchBj("1500");//提货围栏半径 默认100米
			bap.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap);
	        BasicAddressParam bap2 = new BasicAddressParam();
	        bap2.setPutgoodsId(Long.parseLong(bputr.getId().toString()));
        	bap2.setAddress(ExcelItem.getSetUnit());
        	bar = basicAddressService.findBySpec(bap2);
			oodp.setSetLocation(bar.getAddress());//装货地址
			oodp.setSetLocationId(Long.parseLong(bar.getId().toString()));//装货地址id
			oodp.setSetPeople("None");//联系人
			oodp.setSetTel(bar.getTel());//联系电话
		} 

        //查询卸货单位 是否存在
        BasicPutgoodsParam bpgp3 = new BasicPutgoodsParam();
        bpgp3.setPutgoodsCustomerId(basicCustomer.getId());//客户id
        bpgp3.setPutgoodsName(ExcelItem.getGetUnitName());//单位名称  (Excel导入数据中 的收货客户)
        if(ToolUtil.isNotEmpty(ExcelItem.getGetLocation())) {
        	bpgp3.setLocationAddress(ExcelItem.getGetLocation());
    	}
        BasicPutgoodsResult bputr2 = basicPutgoodsService.findBySpec(bpgp3,null);
        if (bputr2==null) {
        	bpgp3.setPutgoodsOperateName(basicCustomer.getCustomerName());//客户名称
        	bpgp3.setDeliverId(user.getDeliverId());
        	bpgp3.setDeptId(user.getDeptId());
        	bpgp3.setUnitNumber(ExcelItem.getGetUnitNumber());//单位编号(Excel导入数据中 的客户编号)
        	bpgp3.setPutgoodsContacts(ExcelItem.getGetPeople());
        	basicPutgoodsService.add(bpgp3);
        	dealWithParam.setNewCustomersflag(true);
        	dealWithParam.setNewCustomers(dealWithParam.getNewCustomers()+"New Consignee Unit："+ExcelItem.getGetUnitName()+"；");
	        BasicPutgoodsParam bpgp4 = new BasicPutgoodsParam();
	        bpgp4.setPutgoodsCustomerId(basicCustomer.getId());//客户id
	        bpgp4.setPutgoodsName(ExcelItem.getGetUnitName());//单位名称
	        bputr2 = basicPutgoodsService.findBySpec(bpgp4,null);
		}
        oodp.setGetUnit(bputr2.getPutgoodsName());//卸货单位
        oodp.setGetUnitId(Long.parseLong(bputr2.getId().toString()));//卸货单位id
        //查询卸货地点 是否存在
        BasicAddressParam bap3 = new BasicAddressParam();
        bap3.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));//单位id
        if(ToolUtil.isNotEmpty(ExcelItem.getGetLocation())) {
            bap3.setAddress(ExcelItem.getGetLocation());
    	}
        BasicAddressResult bar2 = basicAddressService.findBySpec(bap3);//通过单位id 地址 查询
        if(bar2 != null) {
			oodp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
			oodp.setKilometer(bar2.getKilometer());
        	if(ToolUtil.isNotEmpty(ExcelItem.getGetLocation())) {
            	bap3.setAddress(ExcelItem.getGetLocation());
    			oodp.setGetLocation(ExcelItem.getGetLocation());//卸货地址
        	} else {
        		oodp.setGetLocation(bar2.getAddress());//卸货地址
        	}
        	if(ToolUtil.isNotEmpty(ExcelItem.getGetPeople())) {
            	bap3.setContacts(ExcelItem.getGetPeople());
    			oodp.setGetPeople(ExcelItem.getGetPeople());//联系人
        	} else {
        		oodp.setGetPeople(bar2.getContacts());//联系人
        	}
        	if(ToolUtil.isNotEmpty(ExcelItem.getGetUnitTel())) {
            	bap3.setTel(ExcelItem.getGetUnitTel());
    			oodp.setGetTel(ExcelItem.getGetUnitTel());//联系电话
        	} else {
        		oodp.setGetTel(bar2.getTel());//联系电话
        	}       	
        	bap3.setId(bar2.getId());
        	basicAddressService.update(bap3);
        } else if (bar2==null&&ToolUtil.isEmpty(ExcelItem.getGetLocation())) {//如果没有地址 并且Excel中收货客户地址 为空，  卸货地址为 单位名称
        	bap3.setAddress(bputr2.getPutgoodsName());//地点 为单位名称
			bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
			bap3.setTel(bputr2.getPutgoodsTel());//联系电话 (单位 的联系电话)
			bap3.setContacts(bputr2.getPutgoodsContacts());
			bap3.setSwitchWl("1");
			bap3.setSwitchBj("1500");//提货围栏半径 默认100米
			bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap3);
	        BasicAddressParam bap4 = new BasicAddressParam();
	        bap4.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));
        	bap4.setAddress(bputr2.getPutgoodsName());
        	bar2 = basicAddressService.findBySpec(bap4);
			oodp.setGetLocation(bar2.getAddress());//卸货地址
			oodp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
			oodp.setGetPeople(bar2.getContacts());//联系人
			oodp.setGetTel(bar2.getTel());//联系电话
		} else if(bar2==null&&ToolUtil.isNotEmpty(ExcelItem.getGetLocation())){//如果没有地址  Excel中有收货客户地址  新增基础数据 地址
        	bap3.setAddress(ExcelItem.getGetLocation());//地点 (Excel中收货客户地址)
			bap3.setPutgoodsName(bputr2.getPutgoodsName());//单位名称
			bap3.setTel(ExcelItem.getGetUnitTel());//联系电话 (Excel中的 收货客户电话)
			bap3.setContacts(ExcelItem.getGetPeople());
			bap3.setSwitchWl("1");
			bap3.setSwitchBj("1500");//提货围栏半径 默认100米
			bap3.setSwitchBj2("2000");//收货围栏半径 默认100米
			basicAddressService.add(bap3);
	        BasicAddressParam bap4 = new BasicAddressParam();
	        bap4.setPutgoodsId(Long.parseLong(bputr2.getId().toString()));
        	bap4.setAddress(ExcelItem.getGetLocation());
        	bar2 = basicAddressService.findBySpec(bap4);
			oodp.setGetLocation(bar2.getAddress());//卸货地址
			oodp.setGetLocationId(Long.parseLong(bar2.getId().toString()));//卸货地址id
			oodp.setGetPeople(bar2.getContacts());//联系人
			oodp.setGetTel(bar2.getTel());//联系电话
		} 
	}

	@Override
	public LayuiPageInfo getUnitlistPage(OutOrderParam param, String condition,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getUnitlistPage(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public LayuiPageInfo ConfirmlistPageBySpec(OutOrderParam param, String condition,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.ConfirmlistPageBySpec(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public LayuiPageInfo QuerylistPageBySpec(OutOrderParam param, String condition,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.QuerylistPageBySpec(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}
	
	@Override
	public LayuiPageInfo PrintlistPageBySpec(OutOrderParam param, String condition,Long operateId) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.PrintlistPageBySpec(pageContext, param,condition, operateId);
        return LayuiPageFactory.createPageInfo(page);
	}

	@Override
	public boolean saveBatchList(List<OutOrderParam> list) {
		return this.baseMapper.saveBatchList(list);
	}

	@Resource
    private DeptService deptService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 处理出库订单导入_恒安
	 */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData getExceldata_ha(MultipartFile file, OutOrderParam outOrderParam, ResponseData data) throws Exception {
		String fileName = file.getOriginalFilename();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Incorrect uploaded file format");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
//        if(sheet!=null){
//			data.setMessage("未获取到数据");
//			data.setSuccess(false);
//        }

		List<OutOrderExcelItem> list = new ArrayList<OutOrderExcelItem>();
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            OutOrderExcelItem excelItem = new OutOrderExcelItem();

            String consignmentdate = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(3));
            excelItem.setConsignmentdate(consignmentdate);//发货日期

            String getUnitNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(4));
            excelItem.setGetUnitNumber(getUnitNumber);//客户编号

            String getUnitName = getCellValue(row.getCell(5));
            excelItem.setGetUnitName(getUnitName);//收货客户

            String warehouseNumber = getCellValue(row.getCell(6));
            excelItem.setWarehouseNumber(warehouseNumber);//仓库编号

            String warehouseName = getCellValue(row.getCell(7));
            excelItem.setWarehouseName(warehouseName);//仓库名称
            

            String customerNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(8));
            excelItem.setCustomerNumber(customerNumber);//客户单号

            String goodsNumber = getCellValue(row.getCell(9));
    		excelItem.setGoodsNumber(goodsNumber);//商品编号

            String goodsName = getCellValue(row.getCell(10));
            excelItem.setGoodsName(goodsName);//商品名称

//            String batch = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(12));
//            excelItem.setBatch(batch);//批次号
            
            String unit = getCellValue(row.getCell(13));
            excelItem.setUnit(unit);//单位
            
            String bignum = getCellValue(row.getCell(14));
            excelItem.setBignum(bignum);//大包数量
            
            String outVolume = getCellValue(row.getCell(15));
            excelItem.setOutVolume(outVolume);//体积
            
//            String price = getCellValue(row.getCell(16));
//            excelItem.setPrice(price);//单价
            
//            String detailedMoney = getCellValue(row.getCell(27));
//            excelItem.setDetailedMoney(detailedMoney);//金额
            
//            String detailedWeight = getCellValue(row.getCell(28));
//            excelItem.setDetailedWeight(detailedWeight);//重量
            
            String getUnitTel = getCellValue(row.getCell(29));
            excelItem.setGetUnitTel(getUnitTel);//收货客户电话
            
            String getLocation = getCellValue(row.getCell(30));
            excelItem.setGetLocation(getLocation);//收货客户地址
            
            list.add(excelItem);
        }

		if(outOrderParam.getOutCustomerId()==null||outOrderParam.getTransportWay()==null) {
			data.setSuccess(false);
			data.setMessage("Please fill in the basic order information!");
			return data;
		}
		List<OutOrderParam> outorderList = new ArrayList<OutOrderParam>();//批量保存的 出库订单list
		List<OrderTransportParam> transportList = new ArrayList<OrderTransportParam>();//批量保存的 货运订单list
		List<OutOrderDetailedParam> detailedList = new ArrayList<OutOrderDetailedParam>();//批量保存的 出库订单明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(outOrderParam.getOutCustomerId());//客户信息
		User user = userService.getcurrentUser();
		Long DeptId = user.getDeptId();
		Long DeliverId = user.getDeliverId();
		String name = user.getName();
		String trayCode = getOperateIdOrderPrefix(user);

		//查询最新 出库订单
    	OutOrder outOrder = this.findByTheLastOne();
    	int outOrderNumber = 1;
        if (outOrder != null){
        	outOrderNumber = outOrder.getId()+1;
        }
    	DealWithParam dealWithParam = new DealWithParam();
    	dealWithParam.setNewCustomersflag(false);
        //查询最新 货运订单
    	OrderTransport t = orderTransportService.findByThelastone();
    	int transportNumber = 1;
    	if (t!=null) {
    		transportNumber = t.getId()+1;
		} 
		for (OutOrderExcelItem ExcelItem : list) {
			if (ToolUtil.isEmpty(ExcelItem.getWarehouseName())&&ToolUtil.isEmpty(ExcelItem.getCustomerNumber())&&ToolUtil.isEmpty(ExcelItem.getGoodsNumber())) {
				break;
			}
			if(ToolUtil.isEmpty(ExcelItem.getConsignmentdate())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Shipping date in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getWarehouseName())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse name in imported data cannot be empty!");
				return data;
			}
			BasicWarehouseParam bawp = new BasicWarehouseParam();
			bawp.setWarehouseName(ExcelItem.getWarehouseName());
			bawp.setDeliverId(DeliverId);
			BasicWarehouseResult bawr = basicWarehouseService.findBySpec(bawp,DeptId,user.getOperateId());//仓库信息
			if(bawr==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse in imported data does not exist!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getCustomerNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Customer order No. in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getGetUnitName())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Consignee in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getGoodsNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Commodity Code in imported data cannot be empty!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			OutOrderParam oop = new OutOrderParam();
			oop.setCustomerNumber(ExcelItem.getCustomerNumber());//导入数据 (客户单号)
			OutOrderResult oorOrderResult = this.findBySpec(oop,null);
			//如果不存在
			if (oorOrderResult==null) {
				//新增出库订单
				OutOrderParam oodp = new OutOrderParam();
	        	oodp.setOutOrderNumber(trayCode+"-"+"CK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+outOrderNumber);//系统单号
				oodp.setOutOrderStatus("PENDING_SUBMIT");//单据状态
		        oodp.setOutCustomerId(outOrderParam.getOutCustomerId());//所属客户id
		        oodp.setOutCustomerName(basicCustomer.getCustomerName());//所属客户名称
		        oodp.setCustomerNumber(ExcelItem.getCustomerNumber());//客户单号 (Excel导入数据中 客户单号)
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		        try {
					Date date = sdf.parse(getDatesssss());
			        oodp.setOutTime(date);
				} catch (Exception e) {
					e.printStackTrace();
				}
		        oodp.setOutWay("配送");
		        oodp.setOutStorehouseId(Long.parseLong(bawr.getId().toString()));//仓库id
		        oodp.setStorehouseName(bawr.getWarehouseName());//仓库名称
		        oodp.setSettlementWay(outOrderParam.getSettlementWay());//结算方式
		        oodp.setTransportWay(outOrderParam.getTransportWay());//运输方式
		        oodp.setCarNumber(ExcelItem.getCarNumber());//车牌号 (Excel导入数据中 车号)
		        toDealWith(oodp,basicCustomer,ExcelItem,dealWithParam);//处理单位和地址

		        try {
		        	String consignmentdate = ExcelItem.getConsignmentdate();
					oodp.setSetMentiontime(consignmentdate);//发货日期
				} catch (Exception e) {
					oodp.setSetMentiontime(getDatesssss());//发货日期
				}
				oodp.setNote(ExcelItem.getNodes());//备注
		        oodp.setDeptId(DeptId);
		        oodp.setDeliverId(DeliverId);
		        oodp.setCreateUserName(name);
		        oodp.setFactoryNumber(ExcelItem.getFactory());//工厂编号
		        oodp.setFactoryName(ExcelItem.getFactoryName());//工厂名称
		        oodp.setTurnNumber(ExcelItem.getTurnNumber());//转储编号
		        oodp.setTransportNumber(ExcelItem.getTransportNumber());//货运编号
		        oodp.setProcurementNumber(ExcelItem.getPurchaserNumber());//客户采购订单编号
		        oodp.setCreateTime(new Date());
		    	boolean whether = false;//判断客户单号  是否重复
		    	for (OutOrderParam opp2 : outorderList) {
					if (opp2.getCustomerNumber().equals(oodp.getCustomerNumber())) {
						whether = true;
						oorOrderResult = new OutOrderResult();
		    			ToolUtil.copyProperties(opp2,oorOrderResult);
					}
				}
		    	if (!whether) {
		    		outorderList.add(oodp);
		    		outOrderNumber++;
					oorOrderResult = new OutOrderResult();
	    			ToolUtil.copyProperties(oodp,oorOrderResult);
				}
		    	oodp = new OutOrderParam();
			} else {
				//如果 导入的客户单号 已存在
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Customer order number " + oorOrderResult.getCustomerNumber() + " already exists in imported data! ");
				return data;
			}
			boolean hy = true;//true 生成  false不生成
			if (hy) {
		        if(basicCustomer != null && ToolUtil.isNotEmpty(basicCustomer.getWmsAddtms())&&basicCustomer.getWmsAddtms().equals("1")) {
		        	//生成货运订单
		        	OrderTransportParam otp = new OrderTransportParam();
		        	otp.setCustomerOrder(oorOrderResult.getCustomerNumber());//客户单号
		        	OrderTransportResult otr = orderTransportService.findBySpec(otp,null);
		        	if (otr==null) {
		        		otp.setOperateId(Long.parseLong(bawr.getWarehouseOperateId().toString()));//分公司id
		        		otp.setOperateName(bawr.getWarehouseOperateName());//公司名称
		        		otp.setTransportNumber(trayCode+"-"+"HY-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+transportNumber);
		        		otp.setCustomerId(Long.parseLong(basicCustomer.getId().toString()));//客户id
		        		otp.setCustomerName(basicCustomer.getCustomerName());//客户名称
		        		otp.setUndertime(getDatesssss());//下单时间
		        		otp.setOrderNumber(oorOrderResult.getOutOrderNumber());//订单号
		        		otp.setTstate("h");//状态为h
		        		otp.setSetUnit(oorOrderResult.getSetUnit());//装货单位
		        		otp.setSetUnitId(oorOrderResult.getSetUnitId());//装货单位id
		        		otp.setSetLocation(oorOrderResult.getSetLocation());//装货地点
		        		otp.setSetLocationId(oorOrderResult.getSetLocationId());//装货地点id
		        		otp.setSetPeople(oorOrderResult.getSetPeople());//联系人
		        		otp.setSetTel(oorOrderResult.getSetTel());//联系电话
		        		
		        		try {
		        			String consignmentdate = ExcelItem.getConsignmentdate();
		        			otp.setSetMentiontime(consignmentdate);//发货日期
		        		} catch (Exception e) {
		        			otp.setSetMentiontime(getDatesssss());//发货日期
		        		}
		        		otp.setNodes(oorOrderResult.getNote());//备注
		        		otp.setDeptId(DeptId);
		        		otp.setDeliverId(DeliverId);
		        		
		        		otp.setGetUnit(oorOrderResult.getGetUnit());//卸货单位
		        		otp.setGetUnitId(oorOrderResult.getGetUnitId());//卸货单位id
		        		otp.setGetLocation(oorOrderResult.getGetLocation());//卸货地点
		        		otp.setGetLocationId(oorOrderResult.getGetLocationId());//卸货地点id
		        		otp.setGetPeople(oorOrderResult.getGetPeople());//联系人
		        		otp.setGetTel(oorOrderResult.getGetTel());//联系电话
		        		
		        		otp.setCreateName(name);
		        		otp.setOrderSource("WMS");
		        		otp.setCreateTime(new Date());
		        		otp.setCreateUser(user.getUserId());
		        		BasicAddress basicAddress = basicAddressService.getById(otp.getGetLocationId());
		        		if(basicAddress != null) {
		        			otp.setLineId(basicAddress.getLineId());
		        			otp.setLineName(basicAddress.getLineName());
		        		}
		        		boolean whether = false;//判断客户单号  是否重复
		        		for (OrderTransportParam orp2 : transportList) {
		        			if (orp2.getCustomerOrder().equals(otp.getCustomerOrder())) {
		        				whether = true;
		        			}
		        		}
		        		if (!whether) {
		        			transportList.add(otp);
		        			transportNumber++;
		        		}
		        		otp = new OrderTransportParam();
		        		otr = new OrderTransportResult();
		        	} 
		        }
			}
			
			//判断商品是否存在
			BasicGoodsParam bgp = new BasicGoodsParam();
			bgp.setGoodsNumber(ExcelItem.getGoodsNumber());
			bgp.setGoodsCustomerId(Integer.parseInt(outOrderParam.getOutCustomerId().toString()));
			bgp.setDeliverId(DeliverId);
			BasicGoodsResult bgr = basicGoodsService.findBySpec(bgp,null);
			if (bgr==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Commodity in imported data does not exist! Code:"+ExcelItem.getGoodsNumber());
				return data;
			}
			//计算 单价，体积单位
			BigDecimal as = new BigDecimal(0);
			BigDecimal outnum = new BigDecimal(ExcelItem.getBignum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应出数量
			BigDecimal outvolume =  as;//应入体积
			if(ToolUtil.isNotEmpty(ExcelItem.getOutVolume())) {
				outvolume =  new BigDecimal(ExcelItem.getOutVolume());
			}
			BigDecimal outMoney = as;//金额
			if(ToolUtil.isNotEmpty(ExcelItem.getPrice())) {
				outMoney =  new BigDecimal(ExcelItem.getPrice());
			}
			BigDecimal v = as;//体积单位
			if(bgr.getGoodsVolume()!=null){
				v = new BigDecimal(bgr.getGoodsVolume());//体积单位
			}
			BigDecimal u = as;//计费指定价
			if(bgr.getGoodsCharging()!=null){
				u = new BigDecimal(bgr.getGoodsCharging());
			}
			BigDecimal w = as;//重量单位
			if(bgr.getGoodsWeight()!=null){
				w = new BigDecimal(bgr.getGoodsWeight());//重量单位
			}
			if (outvolume.compareTo(as)==1) {//大于 返回1 
				BigDecimal newv = outvolume.divide(outnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
				if(v.compareTo(newv) != 0) {//判断是否更新商品体积
					v = newv;
					BasicGoodsParam basicGoodsParamupdate = new BasicGoodsParam();
					basicGoodsParamupdate.setGoodsVolume(newv.toString());
					basicGoodsParamupdate.setId(bgr.getId());
					basicGoodsService.update(basicGoodsParamupdate);
				}
			}
			if(outMoney.compareTo(as)==1) {//大于 返回1 
				u = outMoney.divide(outnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
			}
			//生成出库订单明细
			String batch = ExcelItem.getBatch();//导入生产日期 20210714
			StringBuffer strBuffer = new StringBuffer();
			if(ToolUtil.isNotEmpty(batch)) {
				if(batch.length()==10) {
					try {
						batch = "20"+batch.substring(0,6);//恒安导入 2111120456
					} catch (Exception e) {
		                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
						data.setSuccess(false);
						data.setMessage("Batch exception! Please check the batch format.");
						return data;
					}
				} else {
					try {
						batch = batch.substring(0, 8);//贝因美导入 20210613
					} catch (Exception e) {
		                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
						data.setSuccess(false);
						data.setMessage("Batch exception! Please check the batch format.");
						return data;
					}
				}
				char[] dataArray = batch.toCharArray();
				for(int i = 0; i < dataArray.length; i++){
				strBuffer.append(dataArray[i]);
					if(i == 3 || i == 5){
					strBuffer.append("-");
					}
				}
			}
			
			OutOrderDetailedParam oodp = new OutOrderDetailedParam();
			oodp.setDetailedFactory(ExcelItem.getFactory());//工厂号
			oodp.setDetailedOutNumber(oorOrderResult.getOutOrderNumber());//出库订单编号
			oodp.setDetailedGoodscode(bgr.getGoodsNumber());//商品编号
			oodp.setDetailedGoodsId(Long.parseLong(bgr.getId().toString()));//商品id
			oodp.setDetailedGoodsname(bgr.getGoodsName());//商品名称
			oodp.setGoodsNo(bgr.getGoodsNo());
			oodp.setDetailedPutbalenum(outnum.toString());//大包数量
			oodp.setDetailedNumber(outnum.toString());//数量
			oodp.setDetailedWeight(w.toString());//重量
			oodp.setDetailedOutWeight(w.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应出重量
			oodp.setDetailedVolume(v.toString());//体积
			oodp.setDetailedOutVolume(v.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应出体积
			oodp.setDetailedPrice(u.toString());//单价
			oodp.setDetailedMoney(u.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//金额
			if (ToolUtil.isNotEmpty(batch)) {
				oodp.setDetailedBatchnumber(batch);//批次号
				oodp.setDetailedDate(strBuffer.toString());//生产日期
			}
			oodp.setDetailedRebubbles(bgr.getGoodsHeavybubble());//重泡货
			oodp.setDetailedLargeclass(bgr.getGoodsBigtype());//商品大类
			oodp.setDetailedGoodstype(bgr.getGoodsType());//商品类别
			oodp.setDetailedPutcondition(bgr.getGoodsCondition());//保管条件
			if(ToolUtil.isNotEmpty(ExcelItem.getUnit())) {
				oodp.setGoodsUnit(ExcelItem.getUnit());
			} else {
				oodp.setGoodsUnit(bgr.getGoodsUnit());//单位
			}
			oodp.setDetailedPacking(bgr.getGoodsPacking());//商品包装
			oodp.setGoodsSpecs(bgr.getGoodsSpecs());//规格
			oodp.setCreateTime(new Date());
			oodp.setCreateUser(user.getUserId());
			detailedList.add(oodp);
			oodp = new OutOrderDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(outorderList);
			if (transportList.size()>0) {
				orderTransportService.saveBatchList(transportList);
			}
			outOrderDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		if (dealWithParam.isNewCustomersflag()) {
			data.setCode(450);
			data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", "")+"Please promptly maintain the route and correct the address for the new unit! To avoid affecting vehicle dispatching and driver delivery.");
		}
        return data;
	}

	/**
	 * 处理出库订单导入
	 */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData getExceldata(MultipartFile file, OutOrderParam outOrderParam, ResponseData data) throws Exception {
		String fileName = file.getOriginalFilename();
		
		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Incorrect uploaded file format");
			data.setSuccess(false);
        }

		boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
//        if(sheet!=null){
//			data.setMessage("未获取到数据");
//			data.setSuccess(false);
//        }

		List<OutOrderExcelItem> list = new ArrayList<OutOrderExcelItem>();
        for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
        	Row row = sheet.getRow(r);
            if (row == null){
                continue;
            }
            OutOrderExcelItem excelItem = new OutOrderExcelItem();

            String consignmentdate = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(0));
            excelItem.setConsignmentdate(consignmentdate);//发货日期

            String getUnitNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(1));
            excelItem.setGetUnitNumber(getUnitNumber);//客户编号

            String getUnitName = getCellValue(row.getCell(2));
            excelItem.setGetUnitName(getUnitName);//收货客户

            String warehouseNumber = getCellValue(row.getCell(3));
            excelItem.setWarehouseNumber(warehouseNumber);//仓库编号

            String warehouseName = getCellValue(row.getCell(4));
            excelItem.setWarehouseName(warehouseName);//仓库名称

            String customerNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(5));
            excelItem.setCustomerNumber(customerNumber);//客户单号

            String goodsNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(6));
    		excelItem.setGoodsNumber(goodsNumber);//商品编号

            String goodsName = getCellValue(row.getCell(7));
            excelItem.setGoodsName(goodsName);//商品名称

            String batch = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(8));
            excelItem.setBatch(batch);//批次号
            
            String unit = getCellValue(row.getCell(9));
            excelItem.setUnit(unit);//单位

            String bignum = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(10));
            excelItem.setBignum(bignum);//大包数量

            String outVolume = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(11));
            excelItem.setOutVolume(outVolume);//体积

            String price = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(12));
            excelItem.setPrice(price);//单价
            
            String setUnit = getCellValue(row.getCell(13));
            excelItem.setSetUnit(setUnit);//库存地点名称

            String detailedMoney = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(14));
            excelItem.setDetailedMoney(detailedMoney);//金额

            String detailedWeight = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(15));
            excelItem.setDetailedWeight(detailedWeight);//重量

            String getUnitTel = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(16));
            excelItem.setGetUnitTel(getUnitTel);//收货客户电话
            
            String getLocation = getCellValue(row.getCell(17));
            excelItem.setGetLocation(getLocation);//收货客户地址
            
            String getPeople = getCellValue(row.getCell(18));
            excelItem.setGetPeople(getPeople);
            
            String nodes = getCellValue(row.getCell(19));
            excelItem.setNodes(nodes);
            
            list.add(excelItem);
        }

		if(outOrderParam.getOutCustomerId()==null||outOrderParam.getTransportWay()==null) {
			data.setSuccess(false);
			data.setMessage("Please fill in the basic order information!");
			return data;
		}
		List<OutOrderParam> outorderList = new ArrayList<OutOrderParam>();//批量保存的 出库订单list
		List<OrderTransportParam> transportList = new ArrayList<OrderTransportParam>();//批量保存的 货运订单list
		List<OutOrderDetailedParam> detailedList = new ArrayList<OutOrderDetailedParam>();//批量保存的 出库订单明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(outOrderParam.getOutCustomerId());//客户信息
		User user = userService.getcurrentUser();
		Long DeptId = user.getDeptId();
		Long DeliverId = user.getDeliverId();
		String name = user.getName();
		String trayCode = getOperateIdOrderPrefix(user);

		//查询最新 出库订单
    	OutOrder outOrder = this.findByTheLastOne();
    	int outOrderNumber = 1;
        if (outOrder != null){
        	outOrderNumber = outOrder.getId()+1;
        }
        DealWithParam dealWithParam = new DealWithParam();
        dealWithParam.setNewCustomersflag(false);
        //查询最新 货运订单
    	OrderTransport t = orderTransportService.findByThelastone();
    	int transportNumber = 1;
    	if (t!=null) {
    		transportNumber = t.getId()+1;
		} 
		for (OutOrderExcelItem ExcelItem : list) {
			if (ToolUtil.isEmpty(ExcelItem.getWarehouseNumber())&&ToolUtil.isEmpty(ExcelItem.getWarehouseName())&&ToolUtil.isEmpty(ExcelItem.getGoodsNumber())) {
				break;
			}
			if(ToolUtil.isEmpty(ExcelItem.getConsignmentdate())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Shipping date in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getWarehouseNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse Code in imported data cannot be empty!");
				return data;
			}
			BasicWarehouseParam bawp = new BasicWarehouseParam();
			bawp.setWarehouseNumber(ExcelItem.getWarehouseNumber());
			bawp.setDeliverId(DeliverId);
			BasicWarehouseResult bawr = basicWarehouseService.findBySpec(bawp,DeptId,user.getOperateId());//仓库信息
			if(bawr==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse in imported data does not exist!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getGetUnitName())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Consignee in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getGoodsNumber())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Commodity Code in imported data cannot be empty!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			OutOrderParam oop = new OutOrderParam();
			if(ToolUtil.isEmpty(ExcelItem.getCustomerNumber())){
				ExcelItem.setCustomerNumber(trayCode+"-"+"CK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+outOrderNumber);
		    	for (OutOrderParam opp2 : outorderList) {
					if (opp2.getGetUnit().equals(ExcelItem.getGetUnitName())) {
						ExcelItem.setCustomerNumber(opp2.getCustomerNumber());
						break;
					}
				}
			}
			oop.setCustomerNumber(ExcelItem.getCustomerNumber());//导入数据 (客户单号)
			OutOrderResult oorOrderResult = this.findBySpec(oop,user.getOperateId());
			//如果不存在
			if (oorOrderResult==null) {
				//新增出库订单
				OutOrderParam oodp = new OutOrderParam();
	        	oodp.setOutOrderNumber(trayCode+"-"+"CK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+outOrderNumber);//系统单号
				oodp.setOutOrderStatus("PENDING_SUBMIT");//单据状态
		        oodp.setOutCustomerId(outOrderParam.getOutCustomerId());//所属客户id
		        oodp.setOutCustomerName(basicCustomer.getCustomerName());//所属客户名称
		        oodp.setCustomerNumber(ExcelItem.getCustomerNumber());//客户单号 (Excel导入数据中 客户单号)
		        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		        try {
					Date date = sdf.parse(getDatesssss());
			        oodp.setOutTime(date);
				} catch (Exception e) {
					e.printStackTrace();
				}
		        oodp.setOutWay(outOrderParam.getOutWay());//出库方式
		        oodp.setOutStorehouseId(Long.parseLong(bawr.getId().toString()));//仓库id
		        oodp.setStorehouseName(bawr.getWarehouseName());//仓库名称
		        oodp.setSettlementWay(outOrderParam.getSettlementWay());//结算方式
		        oodp.setTransportWay(outOrderParam.getTransportWay());//运输方式
		        oodp.setCarNumber(ExcelItem.getCarNumber());//车牌号 (Excel导入数据中 车号)
		        toDealWith(oodp,basicCustomer,ExcelItem,dealWithParam);//处理单位和地址

		        try {
		        	String consignmentdate = ExcelItem.getConsignmentdate();
					oodp.setSetMentiontime(consignmentdate);//发货日期
				} catch (Exception e) {
					oodp.setSetMentiontime(getDatesssss());//发货日期
				}
				oodp.setNote(ExcelItem.getNodes());//备注
		        oodp.setDeptId(DeptId);
		        oodp.setDeliverId(DeliverId);
		        oodp.setCreateUserName(name);
		        oodp.setFactoryNumber(ExcelItem.getFactory());//工厂编号
		        oodp.setFactoryName(ExcelItem.getFactoryName());//工厂名称
		        oodp.setTurnNumber(ExcelItem.getTurnNumber());//转储编号
		        oodp.setTransportNumber(ExcelItem.getTransportNumber());//货运编号
		        oodp.setProcurementNumber(ExcelItem.getPurchaserNumber());//客户采购订单编号
		        oodp.setNote(ExcelItem.getNodes());
		        oodp.setCreateTime(new Date());
		    	boolean whether = false;//判断客户单号  是否重复
		    	for (OutOrderParam opp2 : outorderList) {
					if (opp2.getCustomerNumber().equals(oodp.getCustomerNumber())) {
						whether = true;
						oorOrderResult = new OutOrderResult();
		    			ToolUtil.copyProperties(opp2,oorOrderResult);
		    			break;
					}
				}
		    	if (!whether) {
		    		outorderList.add(oodp);
	    			outOrderNumber++;
					oorOrderResult = new OutOrderResult();
	    			ToolUtil.copyProperties(oodp,oorOrderResult);
				}
		    	oodp = new OutOrderParam();
			} else {
				//如果 导入的客户单号 已存在
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Customer Order No. in imported data"+oorOrderResult.getCustomerNumber()+"Already exists! ");
				return data;
			}
			boolean hy = true;//true 生成  false不生成
			if (hy) {
		        if(basicCustomer != null && ToolUtil.isNotEmpty(basicCustomer.getWmsAddtms())&&basicCustomer.getWmsAddtms().equals("1")) {
		        	//生成货运订单
		        	OrderTransportParam otp = new OrderTransportParam();
		        	otp.setCustomerOrder(oorOrderResult.getCustomerNumber());//客户单号
		        	OrderTransportResult otr = orderTransportService.findBySpec(otp,null);
		        	if (otr==null) {
		        		otp.setOperateId(Long.parseLong(bawr.getWarehouseOperateId().toString()));//分公司id
		        		otp.setOperateName(bawr.getWarehouseOperateName());//公司名称
		        		otp.setTransportNumber(trayCode+"-"+"HY-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+transportNumber);
		        		otp.setCustomerId(Long.parseLong(basicCustomer.getId().toString()));//客户id
		        		otp.setCustomerName(basicCustomer.getCustomerName());//客户名称
		        		otp.setUndertime(getDatesssss());//下单时间
		        		otp.setOrderNumber(oorOrderResult.getOutOrderNumber());//订单号
		        		otp.setTstate("h");//状态为h
		        		otp.setSetUnit(oorOrderResult.getSetUnit());//装货单位
		        		otp.setSetUnitId(oorOrderResult.getSetUnitId());//装货单位id
		        		otp.setSetLocation(oorOrderResult.getSetLocation());//装货地点
		        		otp.setSetLocationId(oorOrderResult.getSetLocationId());//装货地点id
		        		otp.setSetPeople(oorOrderResult.getSetPeople());//联系人
		        		otp.setSetTel(oorOrderResult.getSetTel());//联系电话
		        		
		        		try {
		        			String consignmentdate = ExcelItem.getConsignmentdate();
		        			otp.setSetMentiontime(consignmentdate);//发货日期
		        		} catch (Exception e) {
		        			otp.setSetMentiontime(getDatesssss());//发货日期
		        		}
		        		otp.setNodes(oorOrderResult.getNote());//备注
		        		otp.setDeptId(DeptId);
		        		otp.setDeliverId(DeliverId);
		        		
		        		otp.setGetUnit(oorOrderResult.getGetUnit());//卸货单位
		        		otp.setGetUnitId(oorOrderResult.getGetUnitId());//卸货单位id
		        		otp.setGetLocation(oorOrderResult.getGetLocation());//卸货地点
		        		otp.setGetLocationId(oorOrderResult.getGetLocationId());//卸货地点id
		        		otp.setGetPeople(oorOrderResult.getGetPeople());//联系人
		        		otp.setGetTel(oorOrderResult.getGetTel());//联系电话
		        		otp.setKilometer(oorOrderResult.getKilometer());
		        		
		        		otp.setCreateName(name);
		        		otp.setOrderSource("WMS");
		        		otp.setCreateTime(new Date());
		        		otp.setCreateUser(user.getUserId());
		        		BasicAddress basicAddress = basicAddressService.getById(otp.getGetLocationId());
		        		if(basicAddress != null) {
		        			otp.setLineId(basicAddress.getLineId());
		        			otp.setLineName(basicAddress.getLineName());
		        		}
		        		boolean whether = false;//判断客户单号  是否重复
		        		for (OrderTransportParam orp2 : transportList) {
		        			if (orp2.getCustomerOrder().equals(otp.getCustomerOrder())) {
		        				whether = true;
		        			}
		        		}
		        		if (!whether) {
		        			transportList.add(otp);
		        			transportNumber++;
		        		}
		        		otp = new OrderTransportParam();
		        		otr = new OrderTransportResult();
		        	} 
		        }
			}
			
			//判断商品是否存在
			BasicGoodsParam bgp = new BasicGoodsParam();
			bgp.setGoodsNumber(ExcelItem.getGoodsNumber());
			bgp.setGoodsCustomerId(Integer.parseInt(outOrderParam.getOutCustomerId().toString()));
			BasicGoodsResult bgr = basicGoodsService.findBySpec(bgp,null);
			if (bgr==null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Commodity in imported data does not exist! Code:"+ExcelItem.getGoodsNumber());
				return data;
			}
			//计算 单价，体积单位
			BigDecimal as = new BigDecimal("0");
			BigDecimal outnum = new BigDecimal(ExcelItem.getBignum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应出数量
			if(outnum.compareTo(as) == 0) {//数量为0  直接忽略
				continue;
			}
			BigDecimal outvolume =  as;//应入体积
			if(ToolUtil.isNotEmpty(ExcelItem.getOutVolume())) {
				outvolume =  new BigDecimal(ExcelItem.getOutVolume());
			}
			BigDecimal u = as;//单价
			if(ToolUtil.isNotEmpty(ExcelItem.getPrice())) {
				u =  new BigDecimal(ExcelItem.getPrice()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
			} else {
				if(bgr.getGoodsCharging()!=null){
					u = new BigDecimal(bgr.getGoodsCharging()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
				}
			}
			BigDecimal v = as;//体积单位
			if(bgr.getGoodsVolume()!=null){
				v = new BigDecimal(bgr.getGoodsVolume()).setScale(8, BigDecimal.ROUND_HALF_DOWN);//体积单位
			}
			BigDecimal w = as;//重量单位
			if(bgr.getGoodsWeight()!=null){
				w = new BigDecimal(bgr.getGoodsWeight());//重量单位
			}
			if (outvolume.compareTo(as)==1) {//大于 返回1 
				BigDecimal newv = outvolume.divide(outnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
				if(v.compareTo(newv) != 0) {//判断是否更新商品体积
					v = newv;
					bgr.setGoodsVolume(newv.toString());
					ToolUtil.copyProperties(bgr, bgp);
					basicGoodsService.update(bgp);
				}
			}
			if(ToolUtil.isNotEmpty(ExcelItem.getDetailedMoney())) {
				BigDecimal DetailedMoney = new BigDecimal(ExcelItem.getDetailedMoney());
				u = DetailedMoney.divide(outnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
			} 
			//生成出库订单明细
			String batch = ExcelItem.getBatch();//导入生产日期 20210714
			StringBuffer strBuffer = new StringBuffer();
			if(ToolUtil.isNotEmpty(batch)) {
				char[] dataArray = batch.toCharArray();
				if(ToolUtil.isEmpty(basicCustomer.getIntercepts()) || basicCustomer.getIntercepts().equals("Yes")) {
					if(ToolUtil.isNotEmpty(batch)) {
						if(batch.length()==10) {
							try {
								batch = "20"+batch.substring(0,6);//恒安导入 2111120456
							} catch (Exception e) {
				                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
								data.setSuccess(false);
								data.setMessage("Batch exception! Please check the batch format.");
								return data;
							}
						} else {
							try {
								batch = batch.substring(0, 8);//贝因美导入 20210613
							} catch (Exception e) {
				                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
								data.setSuccess(false);
								data.setMessage("Batch exception! Please check the batch format.");
								return data;
							}
						}
						for(int i = 0; i < dataArray.length; i++){
						strBuffer.append(dataArray[i]);
							if(i == 3 || i == 5){
							strBuffer.append("-");
							}
						}
					}
				} else {
					for(int i = 0; i < dataArray.length; i++){
					strBuffer.append(dataArray[i]);
					}
				}
			}
			
			OutOrderDetailedParam oodp = new OutOrderDetailedParam();
			oodp.setDetailedFactory(ExcelItem.getFactory());//工厂号
			oodp.setDetailedOutNumber(oorOrderResult.getOutOrderNumber());//出库订单编号
			oodp.setDetailedGoodscode(bgr.getGoodsNumber());//商品编号
			oodp.setDetailedGoodsId(Long.parseLong(bgr.getId().toString()));//商品id
			oodp.setDetailedGoodsname(bgr.getGoodsName());//商品名称
			oodp.setGoodsNo(bgr.getGoodsNo());
			oodp.setDetailedPutbalenum(outnum.toString());//大包数量
			oodp.setDetailedNumber(outnum.toString());//数量
			oodp.setDetailedWeight(w.toString());//重量
			oodp.setDetailedOutWeight(w.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应出重量
			oodp.setDetailedVolume(v.toString());//体积
			oodp.setDetailedOutVolume(v.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应出体积
			oodp.setDetailedPrice(u.toString());//单价
			oodp.setDetailedMoney(u.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//金额
			if (ToolUtil.isNotEmpty(batch)) {
				oodp.setDetailedBatchnumber(batch);//批次号
				oodp.setDetailedDate(strBuffer.toString());//生产日期
			}
			oodp.setDetailedRebubbles(bgr.getGoodsHeavybubble());//重泡货
			oodp.setDetailedLargeclass(bgr.getGoodsBigtype());//商品大类
			oodp.setDetailedGoodstype(bgr.getGoodsType());//商品类别
			oodp.setDetailedPutcondition(bgr.getGoodsCondition());//保管条件
			if(ToolUtil.isNotEmpty(ExcelItem.getUnit())) {
				oodp.setGoodsUnit(ExcelItem.getUnit());
			} else {
				oodp.setGoodsUnit(bgr.getGoodsUnit());//单位
			}
			oodp.setDetailedPacking(bgr.getGoodsPacking());//商品包装
			oodp.setGoodsSpecs(bgr.getGoodsSpecs());//规格
			oodp.setCreateTime(new Date());
			oodp.setCreateUser(user.getUserId());
			detailedList.add(oodp);
			oodp = new OutOrderDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(outorderList);
			if (transportList.size()>0) {
				orderTransportService.saveBatchList(transportList);
			}
			outOrderDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		if (dealWithParam.isNewCustomersflag()) {
			data.setCode(450);
			data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", "")+"Please promptly maintain the route and correct the address for the new unit! To avoid affecting vehicle dispatching and driver delivery.");
		}
        return data;
	}
	
	private static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                return HSSFDateUtil.getJavaDate(cell.getNumericCellValue()).toString();
            } else {
                return new BigDecimal(Double.toString(cell.getNumericCellValue())).toString();
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return StringUtils.trimToEmpty(cell.getStringCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return StringUtils.trimToEmpty(cell.getCellFormula());
        } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
            return "";
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) {
            return "ERROR";
        } else {
            return cell.toString().trim();
        }

    }

	/** 
    * 获取当前日期 yyyy-MM-dd
    * @return
    */  
   public static String getDatesssss() {  
       SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
       return format.format(new Date());  
   }   

	/** 
   * 获取当前日期 yyyy/MM/dd
   * @return
   */  
  public static String getDatesssss2() {  
      SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");  
      return format.format(new Date());  
  }

    @Autowired
    private StorageStockDetailedService storageStockDetailedService;

	private void revoke(StorageOutDetailedResult detailedResult2) {
	   	StorageOutDetailed  storageOutDetailed = storageOutDetailedService.getById(detailedResult2.getId());//拣货明细
   		BigDecimal numinpt = new BigDecimal(storageOutDetailed.getRealNum());//拣货数
	   	StorageStock storageStock = storageStockService.getById(storageOutDetailed.getStockId());//托盘
	   	if(storageStock.getStockId() == null) {
	   		StorageStockParam param2 = new StorageStockParam();
	   		param2.setPositionId(storageStock.getPositionId());
	   		param2.setTrayId(storageStock.getTrayId());
	   		param2.setStockstate("IN_STOCK");
	   		param2.setGoodsId(storageStock.getGoodsId());
	   		param2.setGoodsbatchs(storageStock.getGoodsbatchs());
	   		param2.setWarehouseId(storageStock.getWarehouseId());
	   		StorageStockResult storageStockResult2 = storageStockService.findBySpec2(param2);
	   		if(storageStockResult2 != null) {
		   		StorageStockParam param3 = new StorageStockParam();
		   		BigDecimal snum = new BigDecimal(storageStockResult2.getNum());//托盘数
				BasicGoods basicGoods = basicGoodsService.getById(storageStockResult2.getGoodsId());
				BigDecimal u = new BigDecimal(1);
				if (ToolUtil.isNotEmpty(storageStockResult2.getUnitprice())) {
					u = new BigDecimal(storageStockResult2.getUnitprice());
				}
				BigDecimal v = new BigDecimal(1);
				if(ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
					v = new BigDecimal(basicGoods.getGoodsVolume());
				}
				BigDecimal w = new BigDecimal(1);
				if(ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
					w = new BigDecimal(basicGoods.getGoodsWeight());
				}
       			BigDecimal less = snum.add(numinpt);
       			storageStockResult2.setNum(less.toString());
       			storageStockResult2.setCanNum(less.toString());
       			storageStockResult2.setBalenum(less.toString());
       			storageStockResult2.setStockWeight(less.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
       			storageStockResult2.setStockVolume(less.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
       			storageStockResult2.setStockMoney(less.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				ToolUtil.copyProperties(storageStockResult2,param3);
				storageStockService.update(param3);//修改 原始库存
				
		   		StorageStockParam param4 = new StorageStockParam();
		   		param4.setId(storageStock.getId());
		   		storageStockService.delete(param4);//删除 待出库库存
	   		} else {
	  	   		StorageStockParam storageStockParam = new StorageStockParam();
	  	   		storageStock.setStockstate("IN_STOCK");
	  			ToolUtil.copyProperties(storageStock,storageStockParam);
	  			storageStockService.update(storageStockParam);//修改 库存信息
	   		}
	   	} else {
	   		StorageStockParam storageStockParam = new StorageStockParam();
	   		storageStockParam.setId(Integer.parseInt(storageStock.getStockId().toString()));
	   		storageStockParam.setStockstate("IN_STOCK");
	   		StorageStockResult storageStockResult = storageStockService.findBySpec2(storageStockParam);
	   		if(storageStockResult != null) {
		   		StorageStockParam param2 = new StorageStockParam();
		   		BigDecimal snum = new BigDecimal(storageStockResult.getNum());//托盘数
				BasicGoods basicGoods = basicGoodsService.getById(storageStockResult.getGoodsId());
				BigDecimal u = new BigDecimal(1);
				if (ToolUtil.isNotEmpty(storageStockResult.getUnitprice())) {
					u = new BigDecimal(storageStockResult.getUnitprice());
				}
				BigDecimal v = new BigDecimal(1);
				if(ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
					v = new BigDecimal(basicGoods.getGoodsVolume());
				}
				BigDecimal w = new BigDecimal(1);
				if(ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
					w = new BigDecimal(basicGoods.getGoodsWeight());
				}
       			BigDecimal less = snum.add(numinpt);
       			storageStockResult.setNum(less.toString());
       			storageStockResult.setCanNum(less.toString());
       			storageStockResult.setBalenum(less.toString());
       			storageStockResult.setStockWeight(less.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
       			storageStockResult.setStockVolume(less.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
       			storageStockResult.setStockMoney(less.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				ToolUtil.copyProperties(storageStockResult,param2);
				storageStockService.update(param2);//修改 原始库存
				
		   		StorageStockParam param3 = new StorageStockParam();
		   		param3.setId(storageStock.getId());
		   		storageStockService.delete(param3);//删除 待出库库存
	   		} else {
		   		StorageStockParam param2 = new StorageStockParam();
		   		param2.setTrayId(storageStock.getTrayId());
		   		param2.setStockstate("IN_STOCK");
		   		param2.setGoodsId(storageStock.getGoodsId());
		   		param2.setGoodsbatchs(storageStock.getGoodsbatchs());
		   		param2.setWarehouseId(storageStock.getWarehouseId());
		   		StorageStockResult storageStockResult2 = storageStockService.findBySpec2(param2);
		   		if(storageStockResult2 != null) {
			   		StorageStockParam param3 = new StorageStockParam();
			   		BigDecimal snum = new BigDecimal(storageStockResult2.getNum());//托盘数
					BasicGoods basicGoods = basicGoodsService.getById(storageStockResult2.getGoodsId());
					BigDecimal u = new BigDecimal(1);
					if (ToolUtil.isNotEmpty(storageStockResult2.getUnitprice())) {
						u = new BigDecimal(storageStockResult2.getUnitprice());
					}
					BigDecimal v = new BigDecimal(1);
					if(ToolUtil.isNotEmpty(basicGoods.getGoodsVolume())) {
						v = new BigDecimal(basicGoods.getGoodsVolume());
					}
					BigDecimal w = new BigDecimal(1);
					if(ToolUtil.isNotEmpty(basicGoods.getGoodsWeight())) {
						w = new BigDecimal(basicGoods.getGoodsWeight());
					}
	       			BigDecimal less = snum.add(numinpt);
	       			storageStockResult2.setNum(less.toString());
	       			storageStockResult2.setCanNum(less.toString());
	       			storageStockResult2.setBalenum(less.toString());
	       			storageStockResult2.setStockWeight(less.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       			storageStockResult2.setStockVolume(less.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	       			storageStockResult2.setStockMoney(less.multiply(u).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					ToolUtil.copyProperties(storageStockResult2,param3);
					storageStockService.update(param3);//修改 原始库存
					
			   		StorageStockParam param4 = new StorageStockParam();
			   		param4.setId(storageStock.getId());
			   		storageStockService.delete(param4);//删除 待出库库存
		   		} else {
  		        	UpdateWrapper<StorageStock> updateWrapper = new UpdateWrapper<StorageStock>();
  		        	updateWrapper.eq("id", storageStock.getId());
  		        	updateWrapper.set("stockstate", "IN_STOCK");
  		        	updateWrapper.set("mark", null);
  		        	updateWrapper.set("stock_id", null);
  					storageStockService.update(updateWrapper);//修改 原始库存
		   		}
	   		}
	   	}
	}

	@Override
	public Integer outOrderCount(OutOrderParam outOrderParam, Long warehouseId) {
		return this.baseMapper.outOrderCount(outOrderParam,warehouseId);
	}   

	@Override
	public Integer outNewOrderCount(OutOrderParam outOrderParam, Long warehouseId) {
		return this.baseMapper.outNewOrderCount(outOrderParam,warehouseId);
	}   

	@Override
	public Integer outWeiwanchengOrderCount(OutOrderParam outOrderParam, Long warehouseId) {
		return this.baseMapper.outWeiwanchengOrderCount(outOrderParam,warehouseId);
	}   

	@Override
	public Integer outYuqiOrderCount(OutOrderParam outOrderParam, Long warehouseId) {
		return this.baseMapper.outYuqiOrderCount(outOrderParam,warehouseId);
	}   

	@Override
	public Integer outZuofeiOrderCount(OutOrderParam outOrderParam, Long warehouseId) {
		return this.baseMapper.outZuofeiOrderCount(outOrderParam,warehouseId);
	}

	@Override
	public OutOrderResult getPrintstorageOut(OutOrderParam outOrderParam) {
		return this.baseMapper.getPrintstorageOut(outOrderParam);
	}

	  /**
	   * 撤回出库订单
	   * 云仓
	   */
		@Override
		@Transactional(rollbackFor = Exception.class,timeout=80)
		public ResponseData revoketool(OutOrder outOrder, ResponseData data) {
			User user = userService.getcurrentUser();
			Long deliverId = user.getDeliverId();
			Long deptId = user.getDeptId();
			
			//修改 订单状态
			OutOrderParam outOrderParam = new OutOrderParam();
	        ToolUtil.copyProperties(outOrder,outOrderParam);
	        outOrderParam.setOutOrderStatus("REVOKED");
	        this.update(outOrderParam);
			
	        //合计已拣货
	        StorageOutParam param = new StorageOutParam();
	        param.setOutOrderNumber(outOrder.getOutOrderNumber());
	        param.setOutOrderStatus("revoke");
	        StorageOutResult outResult = storageOutService.findBySpec(param);

	        StorageOutDetailedParam detailedParam = new StorageOutDetailedParam();
	        detailedParam.setStorageOutNumber(outResult.getStorageOutNumber());
	        detailedParam.setStorageOutStatus("PICKED");
	        List<StorageOutDetailedResult> list = storageOutDetailedService.findTotalalready(detailedParam);
	        
	        //修改出库单  
	        int storageOutNumber = 1;
	        StorageOutParam param3 = new StorageOutParam();
	        param3.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
	        StorageOutResult outResult2 = storageOutService.findBySpec(param3);
	        if (list.size()>0&&outResult.getOutOrderStatus().equals("COMPLETED")) {
	            while (outResult2!=null) {
	            	storageOutNumber++;
	            	param3.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
	                outResult2 = storageOutService.findBySpec(param3);
	    		}
	            ToolUtil.copyProperties(outResult,param3);
	            param3.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
	            param3.setOutOrderStatus("REVOKED");
	            param3.setVersion(0);
	            storageOutService.update(param3);
			} else {
	            ToolUtil.copyProperties(outResult,param3);
	            storageOutService.delete(param3);
			}
	        
	        //修改出库明细
	        StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
	        detailedParam2.setStorageOutNumber(outResult.getStorageOutNumber());
	        List<StorageOutDetailedResult> list2 = storageOutDetailedService.findListBySpec(detailedParam2);
	        for (StorageOutDetailedResult detailedResult2 : list2) {
	        	if ("PICKED".equals(detailedResult2.getStorageOutStatus())&&outResult.getOutOrderStatus().equals("COMPLETED")) {
	            	detailedResult2.setStorageOutStatus("REVOKED");
	            	detailedResult2.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
	                ToolUtil.copyProperties(detailedResult2,detailedParam2);
	                storageOutDetailedService.update(detailedParam2);
				} else if ("PICKED".equals(detailedResult2.getStorageOutStatus())) {
					revoke(detailedResult2);
	                ToolUtil.copyProperties(detailedResult2,detailedParam2);
	                storageOutDetailedService.delete(detailedParam2);
				} else {
	                ToolUtil.copyProperties(detailedResult2,detailedParam2);
	                storageOutDetailedService.delete(detailedParam2);
				}
			}
	        
	        if (list.size()>0&&outResult.getOutOrderStatus().equals("COMPLETED")) {
	    		List<ToolStorageStockParam> ssPlist = new ArrayList<ToolStorageStockParam>();//库存list

	    		ToolStorageStockParam ssP = new ToolStorageStockParam();//库存输入类
	        	for (StorageOutDetailedResult detailedResult : list) {
		    		BigDecimal as = new BigDecimal(0);
		    		BigDecimal realNum = new BigDecimal(detailedResult.getRealNum());
		    		if (realNum.compareTo(as)==0) {
						continue;
					}
					
	        		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
	        		BasicGoods basicGoods = basicGoodsService.getById(detailedResult.getStorageGoodsId());
	        		BasicWarehouse basicWarehouse = basicWarehouseService.getById(outOrder.getOutStorehouseId());
	    			bpp.setPositionNumber(detailedResult.getStoragePostionNumber());
	    			bpp.setWarehouseId(basicWarehouse.getId());
	    			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,null,null);//库位信息
	    			
	            	ToolStorageStockParam param2 = new ToolStorageStockParam();
	            	param2.setStockstate("IN_STOCK");
	            	param2.setGoodsId(detailedResult.getStorageGoodsId());
	            	param2.setWarehouseId(outOrder.getOutStorehouseId());
	            	param2.setPositionId(Long.parseLong(bpr.getId().toString()));
	            	ToolStorageStockResult storageStock = toolStorageStockService.findBySpec(param2);
	            	if (storageStock!=null) {
	    	    		BigDecimal b = new BigDecimal(storageStock.getNum());
	    	    		b = b.add(realNum);
	            		try {
	                		BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
	                		BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
	                		BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
	                		storageStock.setStockVolume(b.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	                		storageStock.setStockWeight(b.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
	                		storageStock.setStockMoney(b.multiply(p).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
						} catch (Exception e) {
						}
	            		
	    	    		storageStock.setNum(b.toString());

	    				ToolUtil.copyProperties(storageStock,param2);
	    				toolStorageStockService.update(param2);
					} else {
						//库存明细
		    			ssP.setCustomerId(outOrder.getOutCustomerId());//客户id
		    			ssP.setCustomerName(outOrder.getOutCustomerName());//客户名称
		    			ssP.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));//分公司id
		    			ssP.setOperateName(basicWarehouse.getWarehouseOperateName());//分公司名称
		    			ssP.setWarehouseId(outOrder.getOutStorehouseId());//仓库id
		    			ssP.setWarehouseName(outOrder.getStorehouseName());//仓库名称
		    			ssP.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
		    			ssP.setAreaNumber(bpr.getAreaNumber());//库区编号
		    			ssP.setPositionId(Long.parseLong(bpr.getId().toString()));//库位id
		    			ssP.setPositionNumber(bpr.getPositionNumber());//库位编号
		    			ssP.setGoodsId(detailedResult.getStorageGoodsId());//商品id
		    			ssP.setGoodsName(detailedResult.getStorageGoodsname());//商品名称
		    			ssP.setGoodsNumber(detailedResult.getStorageGoodscode());//商品编号
		    			ssP.setNum(realNum.toString());//应入数量
		    			ssP.setStockWeight(detailedResult.getStorageWeight());//应入重量
		    			ssP.setStockVolume(detailedResult.getStorageVolume());//应入体积
		    			ssP.setUnitprice(basicGoods.getGoodsCharging());//单价
		    			ssP.setStockMoney(detailedResult.getStorageMoney());//金额
		    			ssP.setDeliverId(deliverId);
		    			ssP.setDeptId(deptId);
		    			ssP.setCreateTime(new Date());
		    			ssP.setStockstate("IN_STOCK");
		    			ssP.setGoodsUnit(basicGoods.getGoodsUnit());
		    			ssP.setGoodsSpecs(basicGoods.getGoodsSpecs());
		    			ssPlist.add(ssP);
		    			ssP = new ToolStorageStockParam();
					}
				}
	        	if (ssPlist.size()>0) {
	        		toolStorageStockService.batchAddList(ssPlist);
				}
			}
	        data.setSuccess(true);
			return data;
		}

  /**
   * 撤回出库订单
   */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData revokeS(OutOrder outOrder, ResponseData data) {
		User user = userService.getcurrentUser();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		BasicCustomer c = basicCustomerService.getById(outOrder.getOutCustomerId());
		
		//修改 订单状态
		OutOrderParam outOrderParam = new OutOrderParam();
		outOrderParam.setId(outOrder.getId());
        outOrderParam.setOutOrderStatus("REVOKED");
        this.update(outOrderParam);

        if(c != null && ToolUtil.isNotEmpty(c.getWmsAddtms())&&c.getWmsAddtms().equals("1")) {
        	//修改货运单
        	OrderTransportParam orderTransportParam = new OrderTransportParam();
        	orderTransportParam.setCustomerOrder(outOrder.getCustomerNumber());
        	OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
        	if (orderTransportResult!=null) {
        		//删除调度明细
        		TransportDispatchParam param4 = new TransportDispatchParam();
        		param4.setTransportNumber(orderTransportResult.getTransportNumber());
        		List<TransportDispatchResult> list2 = transportDispatchService.findListBySpec(param4);
        		TransportDispatchParam transportDispatchParam = new TransportDispatchParam();
        		for (TransportDispatchResult dispatchResult : list2) {
        			if(ToolUtil.isNotEmpty(dispatchResult.getDispatchNumber())) {
        				transportDispatchParam.setId(dispatchResult.getId());
        				data = this.transportDispatchService.removeGoodsDispatch(transportDispatchParam ,data,user);
        				if(!data.getSuccess()) {
        					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
        					return data;
        				}
        			} else {
        				data = this.transportDispatchService.removeGoodsWeb(dispatchResult.getTransportNumber(),dispatchResult.getGoodsId(),dispatchResult.getCarnumbger(),data,user);
        				if(!data.getSuccess()) {
        					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚失误
        					return data;
        				}
        			}
        			ToolUtil.copyProperties(dispatchResult,param4);
        			transportDispatchService.delete(param4);
        		}
        		
        		//删除货运明细
        		OrderTransportDetailedParam detailedParam2 = new OrderTransportDetailedParam();
        		detailedParam2.setTransportNumber(orderTransportResult.getTransportNumber());
        		List<OrderTransportDetailedResult> mxlist = orderTransportDetailedService.findListBySpec(detailedParam2);
        		for (OrderTransportDetailedResult detailedr : mxlist) {
        			ToolUtil.copyProperties(detailedr,detailedParam2);
        			orderTransportDetailedService.delete(detailedParam2);
        		}
        		
        		ToolUtil.copyProperties(orderTransportResult,orderTransportParam);
        		orderTransportParam.setTstate("h");
        		orderTransportParam.setTooVolume("0");
        		orderTransportParam.setTooNum("0");
        		orderTransportParam.setStockupareaId(null);
        		orderTransportParam.setAreanumber(null);
        		orderTransportService.update(orderTransportParam);
        	}
        }
        
        if(outOrder.getOutOrderStatus().equals("PENDING_CONFIRMATION")) {
            data.setSuccess(true);
    		return data;
        }
		
        //合计已拣货
        StorageOutParam param = new StorageOutParam();
        param.setOutOrderNumber(outOrder.getOutOrderNumber());
        param.setOutOrderStatus("revoke");
        StorageOutResult outResult = storageOutService.findBySpec(param);

        StorageOutDetailedParam detailedParam = new StorageOutDetailedParam();
        detailedParam.setStorageOutNumber(outResult.getStorageOutNumber());
        detailedParam.setStorageOutStatus("PICKED");
        List<StorageOutDetailedResult> list = storageOutDetailedService.findTotalalready(detailedParam);
        
        //修改出库单  
        int storageOutNumber = 1;
        StorageOutParam param3 = new StorageOutParam();
        param3.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
        StorageOutResult outResult2 = storageOutService.findBySpec(param3);
        if (list.size()>0&&outResult.getOutOrderStatus().equals("COMPLETED")) {
            while (outResult2!=null) {
            	storageOutNumber++;
            	param3.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
                outResult2 = storageOutService.findBySpec(param3);
    		}
            ToolUtil.copyProperties(outResult,param3);
            param3.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
            param3.setOutOrderStatus("REVOKED");
            param3.setVersion(0);
            storageOutService.update(param3);
		} else {
            ToolUtil.copyProperties(outResult,param3);
            storageOutService.delete(param3);
		}
        
        //修改出库明细
        StorageOutDetailedParam detailedParam2 = new StorageOutDetailedParam();
        detailedParam2.setStorageOutNumber(outResult.getStorageOutNumber());
        List<StorageOutDetailedResult> list2 = storageOutDetailedService.findListBySpec(detailedParam2);
        for (StorageOutDetailedResult detailedResult2 : list2) {
        	if ("PICKED".equals(detailedResult2.getStorageOutStatus())&&outResult.getOutOrderStatus().equals("COMPLETED")) {
            	detailedResult2.setStorageOutStatus("REVOKED");
            	detailedResult2.setStorageOutNumber("CH"+outResult.getStorageOutNumber()+"0"+storageOutNumber);
                ToolUtil.copyProperties(detailedResult2,detailedParam2);
                storageOutDetailedService.update(detailedParam2);
			} else if ("PICKED".equals(detailedResult2.getStorageOutStatus())) {
				revoke(detailedResult2);
                ToolUtil.copyProperties(detailedResult2,detailedParam2);
                storageOutDetailedService.delete(detailedParam2);
			} else {
                ToolUtil.copyProperties(detailedResult2,detailedParam2);
                storageOutDetailedService.delete(detailedParam2);
			}
		}
        
        if (list.size()>0&&outResult.getOutOrderStatus().equals("COMPLETED")) {
    		List<StorageStockParam> ssPlist = new ArrayList<StorageStockParam>();//库存list

    		StorageStockParam ssP = new StorageStockParam();//库存输入类
    		BasicTrayParam Tp = new BasicTrayParam();
    		BasicTray basicTray = basicTrayService.findByThelastone();

    		Tp.setTrayState("OCCUPIED");//托盘状态
    		Integer TrayNumber = null;
    		String trayCode = getOperateIdOrderPrefix(user)+"-";
    		if (basicTray!=null) {
    			TrayNumber = (basicTray.getId()+1);
    		} else {
    			TrayNumber = 1;
    		}
    		Tp.setDeliverId(deliverId);
    		Tp.setDeptId(deptId);
        	for (StorageOutDetailedResult detailedResult : list) {
	    		BigDecimal as = new BigDecimal(0);
	    		BigDecimal realNum = new BigDecimal(detailedResult.getRealNum());
	    		if (realNum.compareTo(as)==0) {
					continue;
				}
				
        		BasicPositionParam bpp = new BasicPositionParam();//库位输入类
        		BasicTrayParam btp = new BasicTrayParam();//托盘输入类
        		BasicGoods basicGoods = basicGoodsService.getById(detailedResult.getStorageGoodsId());
        		BasicWarehouse basicWarehouse = basicWarehouseService.getById(outOrder.getOutStorehouseId());
    			bpp.setPositionNumber(detailedResult.getStoragePostionNumber());
    			bpp.setWarehouseId(basicWarehouse.getId());
    			BasicPositionResult bpr = basicPositionService.findBySpec(bpp,null,null);//库位信息
    			btp.setTrayNumber(detailedResult.getTrayNumber());
    			btp.setDeptId(deptId);
    			btp.setDeliverId(deliverId);
    			BasicTrayResult bTr = basicTrayService.findBySpec(btp,user.getOperateId());
    			
            	StorageStockParam param2 = new StorageStockParam();
            	param2.setStockstate("IN_STOCK");
            	param2.setGoodsId(detailedResult.getStorageGoodsId());
            	param2.setWarehouseId(outOrder.getOutStorehouseId());
            	param2.setTrayNumber(detailedResult.getTrayNumber());
            	param2.setGoodsbatchs(detailedResult.getStorageBatchnumber());
            	param2.setPositionId(Long.parseLong(bpr.getId().toString()));
            	StorageStockResult storageStock = storageStockService.findBySpec2(param2);
            	if (storageStock!=null) {
    	    		BigDecimal b = new BigDecimal(storageStock.getNum());
    	    		b = b.add(realNum);
            		try {
                		BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());
                		BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());
                		BigDecimal p = new BigDecimal(basicGoods.getGoodsCharging());
                		storageStock.setStockVolume(b.multiply(v).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                		storageStock.setStockWeight(b.multiply(w).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
                		storageStock.setStockMoney(b.multiply(p).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
					} catch (Exception e) {
					}
            		
    	    		storageStock.setNum(b.toString());
    	    		storageStock.setBalenum(b.toString());
    	    		storageStock.setCanNum(b.toString());

    				ToolUtil.copyProperties(storageStock,param2);
					storageStockDetailedService.addNewDetailed("OUTBOUND", detailedResult.getStorageOutNumber(), "Outbound Reversal", "Inventory Increase"+realNum.toString(), param2,user);//新增 库存流水
    				storageStockService.update(param2);
				} else {
					//库存明细
					if(bTr == null || bTr.getTrayState().equals("OCCUPIED")) {
						BasicTrayParam trayParam = new BasicTrayParam();
						trayParam.setDeliverId(deliverId);
						trayParam.setDeptId(deptId);
						trayParam.setTrayState("IDLE");
						BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
						if (basicTrayResult != null) {
							basicTrayResult.setTrayState("OCCUPIED");
							ToolUtil.copyProperties(basicTrayResult, trayParam);
							basicTrayService.update(trayParam);
			    			ssP.setTrayId(Long.parseLong(trayParam.getId().toString()));//托盘id
			    			ssP.setTrayNumber(trayParam.getTrayNumber());//托盘编号
						} else {
							Tp.setTrayNumber(trayCode+TrayNumber);
							basicTrayService.add(Tp);
							basicTrayResult = basicTrayService.findBySpec(Tp,user.getOperateId());
			    			ssP.setTrayId(Long.parseLong(basicTrayResult.getId().toString()));//托盘id
			    			ssP.setTrayNumber(Tp.getTrayNumber());//托盘编号
							TrayNumber++;
						}
					} else {
		    			ssP.setTrayId(Long.parseLong(bTr.getId().toString()));//托盘id
		    			ssP.setTrayNumber(bTr.getTrayNumber());//托盘编号
		    			bTr.setTrayState("OCCUPIED");
						ToolUtil.copyProperties(bTr, btp);
						basicTrayService.update(btp);
					}
	    			ssP.setCustomerId(outOrder.getOutCustomerId());//客户id
	    			ssP.setCustomerName(outOrder.getOutCustomerName());//客户名称
	    			ssP.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));//分公司id
	    			ssP.setOperateName(basicWarehouse.getWarehouseOperateName());//分公司名称
	    			ssP.setWarehouseId(outOrder.getOutStorehouseId());//仓库id
	    			ssP.setWarehouseName(outOrder.getStorehouseName());//仓库名称
	    			ssP.setAreaId(Long.parseLong(bpr.getPositionAreaId().toString()));//库区id
	    			ssP.setAreaNumber(bpr.getAreaNumber());//库区编号
	    			ssP.setPositionId(Long.parseLong(bpr.getId().toString()));//库位id
	    			ssP.setPositionNumber(bpr.getPositionNumber());//库位编号
	    			ssP.setGoodsId(detailedResult.getStorageGoodsId());//商品id
	    			ssP.setGoodsName(detailedResult.getStorageGoodsname());//商品名称
	    			ssP.setGoodsNumber(detailedResult.getStorageGoodscode());//商品编号
	    			ssP.setNum(realNum.toString());//应入数量
	    			ssP.setBalenum(realNum.toString());//应入数量
	    			ssP.setCanNum(realNum.toString());//应入数量
	    			ssP.setStockWeight(detailedResult.getStorageWeight());//应入重量
	    			ssP.setStockVolume(detailedResult.getStorageVolume());//应入体积
	    			ssP.setUnitprice(basicGoods.getGoodsCharging());//单价
	    			ssP.setStockMoney(detailedResult.getStorageMoney());//金额
	    			ssP.setProducetime(detailedResult.getStorageDate());//生产日期
	    			ssP.setGoodsbatchs(detailedResult.getStorageBatchnumber());//批次
	    			ssP.setPutTime(detailedResult.getRecommendBatchs());
	    			ssP.setDeliverId(deliverId);
	    			ssP.setDeptId(deptId);
	    			ssP.setCreateTime(new Date());
	    			ssP.setCreateUser(user.getUserId());
	    			ssP.setStockstate("IN_STOCK");
	    			ssPlist.add(ssP);
	    			ssP = new StorageStockParam();
				}
			}
        	if (ssPlist.size()>0) {
    			storageStockService.batchAddList(ssPlist);
    			for (StorageStockParam p : ssPlist) {
                	StorageStockParam param2 = new StorageStockParam();
                	param2.setStockstate("IN_STOCK");
                	param2.setGoodsId(p.getGoodsId());
                	param2.setWarehouseId(outOrder.getOutStorehouseId());
                	param2.setTrayNumber(p.getTrayNumber());
                	param2.setGoodsbatchs(p.getGoodsbatchs());
                	StorageStockResult r = storageStockService.findBySpec2(param2);
                	if(r != null) {
    					storageStockDetailedService.addNewDetailedResult("OUTBOUND", outResult.getStorageOutNumber(), "Outbound Reversal", "Inventory Increase"+p.getNum(), r,user);//新增 库存流水
                	}
				}
			}
		}
        data.setSuccess(true);
		return data;
	}

	/**
	 * 不原路返回库存，直接进行添加
	 */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData revokeStrides(OutOrder outOrder, ResponseData data) {
		User user = userService.getcurrentUser();
		Long deliverId = user.getDeliverId();
		Long deptId = user.getDeptId();
		String trayCode = getOperateIdOrderPrefix(user)+"-";

		//托盘信息
		BasicTrayParam Tp = new BasicTrayParam();
		BasicTray basicTray = basicTrayService.findByThelastone();
		Tp.setTrayState("OCCUPIED");//托盘状态
		int TrayNumber = 0;
		if (basicTray!=null) {
			TrayNumber = (basicTray.getId()+1);
		} else {
			TrayNumber = 1;
		}
		Tp.setDeliverId(deliverId);
		Tp.setDeptId(deptId);
		
		//修改 订单状态
		OutOrderParam outOrderParam = new OutOrderParam();
        ToolUtil.copyProperties(outOrder,outOrderParam);
        outOrderParam.setOutOrderStatus("REVOKED");
        this.update(outOrderParam);

		BasicWarehouse basicWarehouse = basicWarehouseService.getById(outOrder.getOutStorehouseId());
		BasicPositionParam BasicPositionParam = new BasicPositionParam();
		BasicPositionParam.setWarehouseId(Integer.parseInt(outOrder.getOutStorehouseId().toString()));
		BasicPositionResult basicPositionResult = basicPositionService.findBySpec(BasicPositionParam,null,null);
		if(basicPositionResult == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
			return ResponseData.error("No storage location found！");
		}
        
        OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
        outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
        List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
        for (OutOrderDetailedResult r : list) {
        	StorageStockParam storageStockParam = new StorageStockParam();
        	storageStockParam.setWarehouseId(outOrder.getOutStorehouseId());
        	storageStockParam.setGoodsId(r.getDetailedGoodsId());
        	storageStockParam.setStockstate("IN_STOCK");
        	StorageStockResult storageStockResult = storageStockService.findBySpec(storageStockParam);
        	if(storageStockResult == null) {
				StorageStockParam param = new StorageStockParam();
				param.setOperateId(Long.parseLong(basicWarehouse.getWarehouseOperateId().toString()));
				param.setOperateName(basicWarehouse.getWarehouseOperateName());
				param.setCustomerId(outOrder.getOutCustomerId());
				param.setCustomerName(outOrder.getOutCustomerName());
				param.setWarehouseId(outOrder.getOutStorehouseId());
				param.setWarehouseName(basicWarehouse.getWarehouseName());
				param.setAreaId(Long.parseLong(basicPositionResult.getPositionAreaId().toString()));
				param.setAreaNumber(basicPositionResult.getAreaNumber());
				param.setPositionId(Long.parseLong(basicPositionResult.getId().toString()));
				param.setPositionNumber(basicPositionResult.getPositionNumber());
				param.setGoodsId(r.getDetailedGoodsId());
				param.setGoodsNumber(r.getDetailedGoodscode());
				param.setGoodsName(r.getDetailedGoodsname());
				param.setProducetime(cn.stylefeng.guns.core.util.DateUtil.getDate());
				param.setGoodsbatchs(cn.stylefeng.guns.core.util.DateUtil.getDateBch());
				param.setPutTime(cn.stylefeng.guns.core.util.DateUtil.getDate());
				param.setStockstate("IN_STOCK");
				param.setDeptId(deptId);
				param.setDeliverId(deliverId);
				param.setCreateTime(new Date());
				
				BasicTrayParam trayParam = new BasicTrayParam();
				trayParam.setDeliverId(deliverId);
				trayParam.setDeptId(deptId);
				trayParam.setTrayState("IDLE");
				BasicTrayResult basicTrayResult = basicTrayService.findBySpec(trayParam,user.getOperateId());
				if (basicTrayResult != null) {
					param.setTrayNumber(basicTrayResult.getTrayNumber());
					basicTrayResult.setTrayState("OCCUPIED");
					ToolUtil.copyProperties(basicTrayResult, trayParam);
					basicTrayService.update(trayParam);
				} else {
					Tp.setTrayNumber(trayCode+TrayNumber);
					basicTrayService.add(Tp);
					param.setTrayNumber(trayCode+TrayNumber);//托盘编号
				}
				param.setNum(r.getDetailedNumber());
				param.setBalenum(r.getDetailedNumber());
				param.setCanNum(r.getDetailedNumber());
				param.setStockWeight(r.getDetailedOutWeight());
				param.setStockVolume(r.getDetailedOutVolume());
				param.setUnitprice(r.getDetailedPrice());
				param.setStockMoney(r.getDetailedMoney());
				storageStockService.add(param);
				TrayNumber++;
        	} else {
    			BasicGoods bG = basicGoodsService.getById(r.getDetailedGoodsId());//商品
    			BigDecimal detailedPutnum = new BigDecimal(r.getDetailedNumber());//出库数量
    			BigDecimal w = new BigDecimal(bG.getGoodsWeight());//重量
    			BigDecimal v = new BigDecimal(bG.getGoodsVolume());//体积
    			BigDecimal u = new BigDecimal(r.getDetailedPrice());//单价compareTo
        		
    			BigDecimal snum = new BigDecimal(storageStockResult.getNum());//库存数量
    			snum = snum.add(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN);
            	StorageStockParam storageStockupdate = new StorageStockParam();
            	storageStockupdate.setId(storageStockResult.getId());
            	storageStockupdate.setNum(snum.toString());
            	storageStockupdate.setBalenum(snum.toString());
            	storageStockupdate.setCanNum(snum.toString());
            	storageStockupdate.setStockWeight(w.multiply(snum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
            	storageStockupdate.setStockVolume(v.multiply(snum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
            	storageStockupdate.setUnitprice(u.toString());
            	storageStockupdate.setStockMoney(u.multiply(snum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
            	storageStockService.update(storageStockupdate);
        	}
		}
		return ResponseData.success();
	}

	/**
	 * 直接扣除库存，不进行拣货
	 */
	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
	public ResponseData outStridesUpdateStorageStock(OutOrder outOrder) {
		OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
		outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
		List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
		for (OutOrderDetailedResult r : list) {
			BasicGoods basicGoods = basicGoodsService.getById(r.getDetailedGoodsId());
			BigDecimal detailedPutnum = new BigDecimal(r.getDetailedNumber());//出库数量
			BigDecimal w = new BigDecimal(basicGoods.getGoodsWeight());//重量
			BigDecimal v = new BigDecimal(basicGoods.getGoodsVolume());//体积
			BigDecimal u = new BigDecimal(basicGoods.getGoodsCharging());//单价compareTo
			BigDecimal as = new BigDecimal(0);
        	
        	StorageStockParam storageStockParam = new StorageStockParam();
        	storageStockParam.setGoodsId(Long.parseLong(basicGoods.getId().toString()));
        	List<StorageStockResult> slist = storageStockService.findListBySpec(storageStockParam,null);
        	if(slist.size()==0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
        		return ResponseData.error(basicGoods.getGoodsNumber()+"Insufficient Inventory！");
        	}
        	for (StorageStockResult sr : slist) {
    			BigDecimal num = new BigDecimal(sr.getNum());//库存数
        		if(num.compareTo(detailedPutnum) == 1) {
        			num = num.subtract(detailedPutnum).setScale(3, BigDecimal.ROUND_HALF_DOWN);
        			StorageStockParam storageStockUpdate = new StorageStockParam();
        			storageStockUpdate.setId(sr.getId());
        			storageStockUpdate.setNum(num.toString());
        			storageStockUpdate.setBalenum(num.toString());
        			storageStockUpdate.setCanNum(num.toString());
        			storageStockUpdate.setStockWeight(w.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
        			storageStockUpdate.setStockVolume(v.multiply(num).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
        			storageStockUpdate.setUnitprice(u.toString());
        			storageStockUpdate.setStockMoney(u.multiply(num).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
        			storageStockService.update(storageStockUpdate);
        			detailedPutnum = as;
        			break;
        		}
        		if(num.compareTo(detailedPutnum) == 0) {
        			StorageStockParam storageStockUpdate = new StorageStockParam();
        			storageStockUpdate.setId(sr.getId());
        			storageStockService.delete(storageStockUpdate);
        			detailedPutnum = as;
        			break;
        		}
        		if(num.compareTo(detailedPutnum) == -1) {
        			StorageStockParam storageStockUpdate = new StorageStockParam();
        			storageStockUpdate.setId(sr.getId());
        			storageStockService.delete(storageStockUpdate);
        			detailedPutnum = detailedPutnum.subtract(num).setScale(3, BigDecimal.ROUND_HALF_DOWN);
        		}
			}
        	if(detailedPutnum.compareTo(as) == 1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
        		return ResponseData.error(basicGoods.getGoodsNumber()+"Insufficient Inventory！");
        	}
		}
        //更新出库订单
        outOrder.setOutOrderStatus("SHIPPED_OUT");
        OutOrderParam param = new OutOrderParam();
        ToolUtil.copyProperties(outOrder,param);
        this.update(param);
		return ResponseData.success();
	}

	@Override
	public void updateBySpec(OutOrderParam outOrderParam) {
		this.baseMapper.updateBySpec(outOrderParam);
	}

	@Override
	public Workbook exportToExcel(OutOrderParam outOrderParam) {
	    //这是表头
		String[] arr = {
				"Customer Order No.",  // 客户单号（行业标准缩写，无歧义）
				"Status",              // 状态（系统通用字段）
				"Shipping Date",       // 发货日期（物流核心术语）
				"Order Creator",       // 制单人员（明确动作+角色）
				"Unloading Unit",      // 卸货单位（与装货单位命名逻辑一致）
				"Unloading Location",  // 卸货地点（Location 对应“地点”场景）
				"Outbound Method",     // 出库方式（Method 精准描述操作方式）
				"Remarks",             // 备注（系统通用备注字段）
				"Volume",              // 体积（物理属性字段，单位隐含适配）
				"Quantity",            // 数量（库存/订单核心量化字段）
				"Goods Value",         // 货值（贴合物流货物价值属性）
				"Unloading Unit ID",   // 卸货单位ID（ID 后缀符合系统字段规范）
				"Kilometers",          // 公里数（明确长度单位，无歧义）
				"Warehouse",           // 仓库（仓储核心术语）
				"Customer",            // 客户（系统通用客户字段）
				"Outbound Order No.",  // 出库订单号（与客户单号命名规范一致）
				"Loading Unit",        // 装货单位（与卸货单位结构对称）
				"Loading Address",     // 装货地址（Address 对应具体地址信息）
				"Order Creation Time", // 制单时间（动作+Creation Time 规范命名）
				"Submission Time",     // 提交时间（动作+Time 结构统一）
				"Submitter",           // 提交人员（简洁角色命名）
				"Confirmation Time",   // 确认时间（延续时间字段命名逻辑）
				"Confirmer",           // 确认人员（与提交人员命名风格一致）
				"Outbound Completion Time" // 完成出库时间（明确动作完成节点）
		};
	    //这是具体数据
	    List<List<String>> list = new ArrayList<>();

    	User user = userService.getcurrentUser();
    	outOrderParam.setDeptId(user.getDeptId());
	    List<OutOrderResult> datalist = this.findListBySpec(outOrderParam,user.getOperateId());
	    for (OutOrderResult r : datalist) {
		    List<String> list1 = new ArrayList<String>();
		    list1.add(r.getCustomerNumber());
		    list1.add(r.getOutOrderStatus());
		    list1.add(r.getSetMentiontime());
		    list1.add(r.getCreateUserName());
		    list1.add(r.getGetUnit());
		    list1.add(r.getGetLocation());
		    list1.add(r.getOutWay());
		    list1.add(r.getNote());
		    list1.add(r.getSumVolume());
		    list1.add(r.getSumNum());
		    list1.add(r.getSumMoney());
		    list1.add(r.getGetUnitId().toString());
		    list1.add(r.getKilometer());
		    list1.add(r.getStorehouseName());
		    list1.add(r.getOutCustomerName());
		    list1.add(r.getOutOrderNumber());
		    list1.add(r.getSetUnit());
		    list1.add(r.getSetLocation());
		    list1.add(r.getCreateTimestr());
		    list1.add(r.getSubmitTimestr());
		    list1.add(r.getSubmitterName());
		    list1.add(r.getExamineTimestr());
		    list1.add(r.getExamineName());
		    list1.add(r.getFinishOutTimestr());
		    list.add(list1);
		    
		}
	    return ExcelWrite.writeToExcelByList(arr, list);
	}

	/**
	 * 保存JST出库单
	 */
	@Override
	public ResponseData saveJstOutOrder(JSONObject data , User user, BasicCustomer byId) {
//		String body = jstDdcx.getBody();
//		OutOrderParam param = new OutOrderParam();
//		outOrderService.add(param);
//		Object data = new JSONObject(jstDdcx.getBody()).get("data");
		Long[] ids = new Long[]{};
		Object datas = new JSONObject(data).get("datas");


		JSONArray jsonArray = new JSONArray(datas);
		for (int i = 0; i < jsonArray.size(); i++) {

			OutOrderParam outOrderParam= new OutOrderParam();
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			Object batchs = jsonObject.get("batchs");


			JSONArray batchsJsonArray = new JSONArray(batchs);
			Object items = jsonObject.get("items");
			JSONArray itemsJsonArray = new JSONArray(items);
			// 订单编号
			Object io_id = jsonObject.get("io_id");
			Object o_id = jsonObject.get("o_id");


			//修改时间
			Object modified = jsonObject.get("modified");

			outOrderParam.setDeptId(user.getDeptId());
			outOrderParam.setDeliverId(user.getDeliverId());
			/**
			 * 出库订单
			 */
			//客户单号
			outOrderParam.setOutCustomerId(132l);
			//客户名称
			outOrderParam.setOutCustomerName(byId.getCustomerName());
			//仓库
			outOrderParam.setOutStorehouseId(96l);
			//仓库名称
			outOrderParam.setStorehouseName("亿家康诚存储仓主仓");
			//出库单号
			outOrderParam.setOutOrderNumber(io_id.toString());
			outOrderParam.setOutWay("配送");
			outOrderParam.setTransportWay("汽运");
			outOrderParam.setSetMentiontime(data.getStr("io_date"));
			if("大坝来货出库专用".equals(jsonObject.get("shop_name"))){
				continue;
			}else if("大坝向黄河北下单专用".equals(jsonObject.get("shop_name"))){
				outOrderParam.setCustomerNumber(o_id.toString()+"大坝");
				outOrderParam.setGetUnit("大坝");
				outOrderParam.setGetUnitId(31683L);
				outOrderParam.setGetLocationId(32069L);
				outOrderParam.setGetLocation("宇佳智慧物流大坝");
			}else if("大单".equals(jsonObject.get("shop_name"))){
				outOrderParam.setCustomerNumber(o_id.toString() +"大单");
				outOrderParam.setGetUnit("大单");
				outOrderParam.setGetUnitId(31684L);

				outOrderParam.setGetLocationId(32068L);
				outOrderParam.setGetLocation("宇佳智慧物流大单");
			}else if("门店预包".equals(jsonObject.get("shop_name"))){
				outOrderParam.setCustomerNumber(o_id.toString() +"预包");
				outOrderParam.setGetUnit("预包");
				outOrderParam.setGetUnitId(32737L);

				outOrderParam.setGetLocationId(33127L);
				outOrderParam.setGetLocation("宇佳智慧物流大单");
			}else { //小货架向大货架下单
				outOrderParam.setCustomerNumber(o_id.toString());
				outOrderParam.setGetUnit("小货架");
				outOrderParam.setGetUnitId(31685L);
				outOrderParam.setGetLocationId(32067L);
				outOrderParam.setGetLocation("宇佳智慧物流小货架");
			}
//			outOrderParam.setGetUnit(jsonObject.get("shop_name").toString());

//			Object buyer_message = jsonObject.get("buyer_message");
			Object buyer_message = jsonObject.get("remark");
			String buyer_messageStr = "";
			if(buyer_message != null){
				buyer_messageStr = buyer_message.toString();
				if(buyer_messageStr.contains("补单")){
					outOrderParam.setCustomerNumber(o_id.toString()+"补单");
					outOrderParam.setGetUnit("补单");
					outOrderParam.setGetUnitId(31689L);
					outOrderParam.setGetLocationId(32073L);
					outOrderParam.setGetLocation("宇佳智慧物流补单");
				}
			}


			outOrderParam.setOutOrderStatus("PENDING_SUBMIT");
			System.out.println(outOrderParam);
			outOrderParam.setSetMentiontime(cn.stylefeng.guns.core.util.DateUtil.getDate());
			outOrderParam.setCreateTime(new Date());
//			OutOrderResult outOrderResult = outOrderService.findbyoutOrderNumber(io_id.toString());
			OutOrderResult outOrderResult = outOrderService.findbyoutOrderNumberByDeptId(o_id.toString(),null,user.getDeptId());
			if(outOrderResult != null){
				continue;
			}
//			outOrderService.add(outOrderParam);
			Integer integer = outOrderService.insertOutOrder(outOrderParam);


			/**
			 * 出库订单详细
			 */
			List<OutOrderDetailedParam> list = new ArrayList<>();
			itemsJsonArray.forEach(item -> {
				JSONObject jsonObject2 = new JSONObject(item);
				OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
				outOrderDetailedParam.setDetailedOutNumber(io_id.toString());
				outOrderDetailedParam.setDetailedNumber(jsonObject2.getStr("qty"));
				outOrderDetailedParam.setDetailedGoodsname(jsonObject2.getStr("name"));
				outOrderDetailedParam.setGoodsUnit(jsonObject2.getStr("unit"));
				outOrderDetailedParam.setDetailedPrice(jsonObject2.getStr("sale_price"));
				outOrderDetailedParam.setDetailedMoney(jsonObject2.getStr("sale_amount"));	// 价格*数量
				outOrderDetailedParam.setCreateTime(new Date());
				outOrderDetailedParam.setDetailedGoodscode(jsonObject2.getStr("sku_id"));

				BasicGoodsParam basicGoodsParam = new BasicGoodsParam();
				basicGoodsParam.setGoodsNumber(jsonObject2.getStr("sku_id"));
				basicGoodsParam.setDeptId(user.getDeptId());
				BasicGoodsResult bySpec = goodsService.findBySpec(basicGoodsParam, user.getOperateId());
				outOrderDetailedParam.setDetailedGoodsId(Long.parseLong(bySpec.getId().toString()));
				batchsJsonArray.forEach(batch -> {
					JSONObject jsonObject3 = new JSONObject(batch);
					if (jsonObject3.getStr("sku_id").equals(jsonObject2.getStr("sku_id"))) {
						if(ToolUtil.isNotEmpty(byId.getGoodsBatchFlag()) && "Yes".equals(byId.getGoodsBatchFlag())){
							outOrderDetailedParam.setDetailedBatchnumber(jsonObject3.getStr("batch_no"));
						}
						outOrderDetailedParam.setDetailedDate(jsonObject3.getStr("product_date"));
					}
				});

				list.add(outOrderDetailedParam);
				//补货
//				replenishmentOrderService.generateReplenishmentOrder(jsonObject2.getStr("sku_id"), jsonObject2.getStr("qty"));
			});

			outOrderDetailedService.saveBatchList(list);
			Integer id = outOrderParam.getId();
			Long[] ids1 = {Long.parseLong(id.toString())};
			jstOutOrderScheduledService.submitJSTOutOrder(ids1);
		}

		return ResponseData.success();
	}

	@Override
	public Integer insertOutOrder(OutOrderParam outOrderParam) {
		return this.baseMapper.insertOutOrder(outOrderParam);
	}

	@Override
	@Transactional(rollbackFor = Exception.class,timeout=80)
    public ResponseData getExceldataLY(MultipartFile file, OutOrderParam outOrderParam, ResponseData data)  throws Exception{
		String fileName = file.getOriginalFilename();

		if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
			data.setMessage("Incorrect uploaded file format");
			data.setSuccess(false);
		}

		boolean isExcel2003 = true;
		if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
			isExcel2003 = false;
		}
		InputStream is = file.getInputStream();
		Workbook wb = null;
		if (isExcel2003) {
			wb = new HSSFWorkbook(is);
		} else {
			wb = new XSSFWorkbook(is);
		}
		Sheet sheet = wb.getSheetAt(0);
//        if(sheet!=null){
//			data.setMessage("未获取到数据");
//			data.setSuccess(false);
//        }

		List<OutOrderExcelItem> list = new ArrayList<OutOrderExcelItem>();
		for (int r = 1; r <= sheet.getLastRowNum()+1; r++) {
			Row row = sheet.getRow(r);
			if (row == null){
				continue;
			}
			OutOrderExcelItem excelItem = new OutOrderExcelItem();

			String consignmentdate = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(66));
			excelItem.setConsignmentdate(consignmentdate);//发货日期

			String getUnitNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(31));
			excelItem.setGetUnitNumber(getUnitNumber);//客户编号

			String getUnitName = getCellValue(row.getCell(32));
			excelItem.setGetUnitName(getUnitName);//收货客户

			String warehouse = getCellValue(row.getCell(1));
			excelItem.setWarehouseNumber(warehouse.split("-")[0]);//仓库编号

//			String warehouseName = getCellValue(row.getCell(4));
			excelItem.setWarehouseName(warehouse.split("-")[0]);//仓库名称

			String customerNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(42));
			excelItem.setCustomerNumber(customerNumber);//客户单号

			String goodsNumber = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(9));
			excelItem.setGoodsNumber(goodsNumber);//商品编号

			String goodsName = getCellValue(row.getCell(10));
			excelItem.setGoodsName(goodsName);//商品名称

			String batch = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(30));
			excelItem.setBatch(batch);//批次号

			String unit = getCellValue(row.getCell(13));
			excelItem.setUnit(unit);//单位

			String bignum = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(11));
			excelItem.setBignum(bignum);//大包数量

			String outVolume = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(53));
			excelItem.setOutVolume(outVolume);//体积

//			String price = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(12));
//			excelItem.setPrice(price);//单价

//			String setUnit = getCellValue(row.getCell(13));
//			excelItem.setSetUnit(setUnit);//库存地点名称

//			String detailedMoney = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(14));
//			excelItem.setDetailedMoney(detailedMoney);//金额
//
//			String detailedWeight = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(15));
//			excelItem.setDetailedWeight(detailedWeight);//重量

			String getUnitTel = cn.stylefeng.guns.core.util.DateUtil.getCellValueByCell(row.getCell(51));
			excelItem.setGetUnitTel(getUnitTel);//收货客户电话

			String getLocation = getCellValue(row.getCell(50));
			excelItem.setGetLocation(getLocation);//收货客户地址

//			String getPeople = getCellValue(row.getCell(18));
//			excelItem.setGetPeople(getPeople);
//
//			String nodes = getCellValue(row.getCell(19));
//			excelItem.setNodes(nodes);

			list.add(excelItem);
		}

		if(outOrderParam.getOutCustomerId()==null||outOrderParam.getTransportWay()==null) {
			data.setSuccess(false);
			data.setMessage("Please fill in the basic order information!");
			return data;
		}
		List<OutOrderParam> outorderList = new ArrayList<OutOrderParam>();//批量保存的 出库订单list
		List<OrderTransportParam> transportList = new ArrayList<OrderTransportParam>();//批量保存的 货运订单list
		List<OutOrderDetailedParam> detailedList = new ArrayList<OutOrderDetailedParam>();//批量保存的 出库订单明细list
		BasicCustomer basicCustomer = basicCustomerService.getById(outOrderParam.getOutCustomerId());//客户信息
		User user = userService.getcurrentUser();
		Long DeptId = user.getDeptId();
		Long DeliverId = user.getDeliverId();
		String name = user.getName();
		String trayCode = getOperateIdOrderPrefix(user);

		//查询最新 出库订单
		OutOrder outOrder = this.findByTheLastOne();
		int outOrderNumber = 1;
		if (outOrder != null){
			outOrderNumber = outOrder.getId()+1;
		}
		DealWithParam dealWithParam = new DealWithParam();
		dealWithParam.setNewCustomersflag(false);
		//查询最新 货运订单
		OrderTransport t = orderTransportService.findByThelastone();
		int transportNumber = 1;
		if (t!=null) {
			transportNumber = t.getId()+1;
		}
		for (OutOrderExcelItem ExcelItem : list) {
			if (ToolUtil.isEmpty(ExcelItem.getWarehouseNumber())&&ToolUtil.isEmpty(ExcelItem.getWarehouseName())&&ToolUtil.isEmpty(ExcelItem.getGoodsNumber())) {
				break;
			}
			if(ToolUtil.isEmpty(ExcelItem.getConsignmentdate())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Shipping date in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getWarehouseNumber())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse Code in imported data cannot be empty!");
				return data;
			}
			BasicWarehouseParam bawp = new BasicWarehouseParam();
			bawp.setWarehouseNumber(ExcelItem.getWarehouseNumber());
			bawp.setDeliverId(DeliverId);
			BasicWarehouseResult bawr = basicWarehouseService.findBySpec(bawp,DeptId,user.getOperateId());//仓库信息
			if(bawr==null) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Warehouse in imported data does not exist!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getGetUnitName())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Consignee in imported data cannot be empty!");
				return data;
			}
			if(ToolUtil.isEmpty(ExcelItem.getGoodsNumber())) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Commodity Code in imported data cannot be empty!");
				return data;
			}
			//通过 导入的客户单号 查询是否存在
			OutOrderParam oop = new OutOrderParam();
			if(ToolUtil.isEmpty(ExcelItem.getCustomerNumber())){
				ExcelItem.setCustomerNumber(trayCode+"-"+"CK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+outOrderNumber);
				for (OutOrderParam opp2 : outorderList) {
					if (opp2.getGetUnit().equals(ExcelItem.getGetUnitName())) {
						ExcelItem.setCustomerNumber(opp2.getCustomerNumber());
						break;
					}
				}
			}
			oop.setCustomerNumber(ExcelItem.getCustomerNumber());//导入数据 (客户单号)
			OutOrderResult oorOrderResult = this.findBySpec(oop,user.getOperateId());
			//如果不存在
			if (oorOrderResult==null) {
				//新增出库订单
				OutOrderParam oodp = new OutOrderParam();
				oodp.setOutOrderNumber(trayCode+"-"+"CK-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+outOrderNumber);//系统单号
				oodp.setOutOrderStatus("PENDING_SUBMIT");//单据状态
				oodp.setOutCustomerId(outOrderParam.getOutCustomerId());//所属客户id
				oodp.setOutCustomerName(basicCustomer.getCustomerName());//所属客户名称
				oodp.setCustomerNumber(ExcelItem.getCustomerNumber());//客户单号 (Excel导入数据中 客户单号)
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				try {
					Date date = sdf.parse(getDatesssss());
					oodp.setOutTime(date);
				} catch (Exception e) {
					e.printStackTrace();
				}
				oodp.setOutWay(outOrderParam.getOutWay());//出库方式
				oodp.setOutStorehouseId(Long.parseLong(bawr.getId().toString()));//仓库id
				oodp.setStorehouseName(bawr.getWarehouseName());//仓库名称
				oodp.setSettlementWay(outOrderParam.getSettlementWay());//结算方式
				oodp.setTransportWay(outOrderParam.getTransportWay());//运输方式
				oodp.setCarNumber(ExcelItem.getCarNumber());//车牌号 (Excel导入数据中 车号)
				toDealWith(oodp,basicCustomer,ExcelItem,dealWithParam);//处理单位和地址

				try {
					String consignmentdate = ExcelItem.getConsignmentdate();
					oodp.setSetMentiontime(consignmentdate);//发货日期
				} catch (Exception e) {
					oodp.setSetMentiontime(getDatesssss());//发货日期
				}
				oodp.setNote(ExcelItem.getNodes());//备注
				oodp.setDeptId(DeptId);
				oodp.setDeliverId(DeliverId);
				oodp.setCreateUserName(name);
				oodp.setFactoryNumber(ExcelItem.getFactory());//工厂编号
				oodp.setFactoryName(ExcelItem.getFactoryName());//工厂名称
				oodp.setTurnNumber(ExcelItem.getTurnNumber());//转储编号
				oodp.setTransportNumber(ExcelItem.getTransportNumber());//货运编号
				oodp.setProcurementNumber(ExcelItem.getPurchaserNumber());//客户采购订单编号
				oodp.setNote(ExcelItem.getNodes());
				oodp.setCreateTime(new Date());
				boolean whether = false;//判断客户单号  是否重复
				for (OutOrderParam opp2 : outorderList) {
					if (opp2.getCustomerNumber().equals(oodp.getCustomerNumber())) {
						whether = true;
						oorOrderResult = new OutOrderResult();
						ToolUtil.copyProperties(opp2,oorOrderResult);
						break;
					}
				}
				if (!whether) {
					outorderList.add(oodp);
					outOrderNumber++;
					oorOrderResult = new OutOrderResult();
					ToolUtil.copyProperties(oodp,oorOrderResult);
				}
				oodp = new OutOrderParam();
			} else {
				//如果 导入的客户单号 已存在
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Customer Order No. in imported data"+oorOrderResult.getCustomerNumber()+"Already exists! ");
				return data;
			}
			boolean hy = true;//true 生成  false不生成
			if (hy) {
				if(basicCustomer != null && ToolUtil.isNotEmpty(basicCustomer.getWmsAddtms())&&basicCustomer.getWmsAddtms().equals("1")) {
					//生成货运订单
					OrderTransportParam otp = new OrderTransportParam();
					otp.setCustomerOrder(oorOrderResult.getCustomerNumber());//客户单号
					OrderTransportResult otr = orderTransportService.findBySpec(otp,null);
					if (otr==null) {
						otp.setOperateId(Long.parseLong(bawr.getWarehouseOperateId().toString()));//分公司id
						otp.setOperateName(bawr.getWarehouseOperateName());//公司名称
						otp.setTransportNumber(trayCode+"-"+"HY-"+cn.stylefeng.guns.core.util.DateUtil.getDateBch()+"-"+transportNumber);
						otp.setCustomerId(Long.parseLong(basicCustomer.getId().toString()));//客户id
						otp.setCustomerName(basicCustomer.getCustomerName());//客户名称
						otp.setUndertime(getDatesssss());//下单时间
						otp.setOrderNumber(oorOrderResult.getOutOrderNumber());//订单号
						otp.setTstate("h");//状态为h
						otp.setSetUnit(oorOrderResult.getSetUnit());//装货单位
						otp.setSetUnitId(oorOrderResult.getSetUnitId());//装货单位id
						otp.setSetLocation(oorOrderResult.getSetLocation());//装货地点
						otp.setSetLocationId(oorOrderResult.getSetLocationId());//装货地点id
						otp.setSetPeople(oorOrderResult.getSetPeople());//联系人
						otp.setSetTel(oorOrderResult.getSetTel());//联系电话

						try {
							String consignmentdate = ExcelItem.getConsignmentdate();
							otp.setSetMentiontime(consignmentdate);//发货日期
						} catch (Exception e) {
							otp.setSetMentiontime(getDatesssss());//发货日期
						}
						otp.setNodes(oorOrderResult.getNote());//备注
						otp.setDeptId(DeptId);
						otp.setDeliverId(DeliverId);

						otp.setGetUnit(oorOrderResult.getGetUnit());//卸货单位
						otp.setGetUnitId(oorOrderResult.getGetUnitId());//卸货单位id
						otp.setGetLocation(oorOrderResult.getGetLocation());//卸货地点
						otp.setGetLocationId(oorOrderResult.getGetLocationId());//卸货地点id
						otp.setGetPeople(oorOrderResult.getGetPeople());//联系人
						otp.setGetTel(oorOrderResult.getGetTel());//联系电话
						otp.setKilometer(oorOrderResult.getKilometer());

						otp.setCreateName(name);
						otp.setOrderSource("WMS");
						otp.setCreateTime(new Date());
						otp.setCreateUser(user.getUserId());
						BasicAddress basicAddress = basicAddressService.getById(otp.getGetLocationId());
						if(basicAddress != null) {
							otp.setLineId(basicAddress.getLineId());
							otp.setLineName(basicAddress.getLineName());
						}
						boolean whether = false;//判断客户单号  是否重复
						for (OrderTransportParam orp2 : transportList) {
							if (orp2.getCustomerOrder().equals(otp.getCustomerOrder())) {
								whether = true;
							}
						}
						if (!whether) {
							transportList.add(otp);
							transportNumber++;
						}
						otp = new OrderTransportParam();
						otr = new OrderTransportResult();
					}
				}
			}

			//判断商品是否存在
			BasicGoodsParam bgp = new BasicGoodsParam();
			bgp.setGoodsNumber(ExcelItem.getGoodsNumber());
			bgp.setGoodsCustomerId(Integer.parseInt(outOrderParam.getOutCustomerId().toString()));
			BasicGoodsResult bgr = basicGoodsService.findBySpec(bgp,null);
			if (bgr==null) {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
				data.setSuccess(false);
				data.setMessage("Commodity in imported data does not exist! Code:"+ExcelItem.getGoodsNumber());
				return data;
			}
			//计算 单价，体积单位
			BigDecimal as = new BigDecimal("0");
			BigDecimal outnum = new BigDecimal(ExcelItem.getBignum()).setScale(3, BigDecimal.ROUND_HALF_DOWN);//应出数量
			if(outnum.compareTo(as) == 0) {//数量为0  直接忽略
				continue;
			}
			BigDecimal outvolume =  as;//应入体积
			if(ToolUtil.isNotEmpty(ExcelItem.getOutVolume())) {
				outvolume =  new BigDecimal(ExcelItem.getOutVolume());
			}
			BigDecimal u = as;//单价
			if(ToolUtil.isNotEmpty(ExcelItem.getPrice())) {
				u =  new BigDecimal(ExcelItem.getPrice()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
			} else {
				if(bgr.getGoodsCharging()!=null){
					u = new BigDecimal(bgr.getGoodsCharging()).setScale(2, BigDecimal.ROUND_HALF_DOWN);
				}
			}
			BigDecimal v = as;//体积单位
			if(bgr.getGoodsVolume()!=null){
				v = new BigDecimal(bgr.getGoodsVolume()).setScale(8, BigDecimal.ROUND_HALF_DOWN);//体积单位
			}
			BigDecimal w = as;//重量单位
			if(bgr.getGoodsWeight()!=null){
				w = new BigDecimal(bgr.getGoodsWeight());//重量单位
			}
			if (outvolume.compareTo(as)==1) {//大于 返回1
				BigDecimal newv = outvolume.divide(outnum,8,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留8位)
				if(v.compareTo(newv) != 0) {//判断是否更新商品体积
					v = newv;
					bgr.setGoodsVolume(newv.toString());
					ToolUtil.copyProperties(bgr, bgp);
					basicGoodsService.update(bgp);
				}
			}
			if(ToolUtil.isNotEmpty(ExcelItem.getDetailedMoney())) {
				BigDecimal DetailedMoney = new BigDecimal(ExcelItem.getDetailedMoney());
				u = DetailedMoney.divide(outnum,3,BigDecimal.ROUND_HALF_DOWN);//(四舍五入保留3位)
			}
			//生成出库订单明细
			String batch = ExcelItem.getBatch();//导入生产日期 20210714
			StringBuffer strBuffer = new StringBuffer();
			if(ToolUtil.isNotEmpty(batch)) {
				char[] dataArray = batch.toCharArray();
				if(ToolUtil.isEmpty(basicCustomer.getIntercepts()) || basicCustomer.getIntercepts().equals("Yes")) {
					if(ToolUtil.isNotEmpty(batch)) {
						if(batch.length()==10) {
							try {
								batch = "20"+batch.substring(0,6);//恒安导入 2111120456
							} catch (Exception e) {
								TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
								data.setSuccess(false);
								data.setMessage("Batch exception! Please check the batch format.");
								return data;
							}
						} else {
							try {
								batch = batch.substring(0, 8);//贝因美导入 20210613
							} catch (Exception e) {
								TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
								data.setSuccess(false);
								data.setMessage("Batch exception! Please check the batch format.");
								return data;
							}
						}
						for(int i = 0; i < dataArray.length; i++){
							strBuffer.append(dataArray[i]);
							if(i == 3 || i == 5){
								strBuffer.append("-");
							}
						}
					}
				} else {
					for(int i = 0; i < dataArray.length; i++){
						strBuffer.append(dataArray[i]);
					}
				}
			}

			OutOrderDetailedParam oodp = new OutOrderDetailedParam();
			oodp.setDetailedFactory(ExcelItem.getFactory());//工厂号
			oodp.setDetailedOutNumber(oorOrderResult.getOutOrderNumber());//出库订单编号
			oodp.setDetailedGoodscode(bgr.getGoodsNumber());//商品编号
			oodp.setDetailedGoodsId(Long.parseLong(bgr.getId().toString()));//商品id
			oodp.setDetailedGoodsname(bgr.getGoodsName());//商品名称
			oodp.setGoodsNo(bgr.getGoodsNo());
			oodp.setDetailedPutbalenum(outnum.toString());//大包数量
			oodp.setDetailedNumber(outnum.toString());//数量
			oodp.setDetailedWeight(w.toString());//重量
			oodp.setDetailedOutWeight(w.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应出重量
			oodp.setDetailedVolume(v.toString());//体积
			oodp.setDetailedOutVolume(v.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//应出体积
			oodp.setDetailedPrice(u.toString());//单价
			oodp.setDetailedMoney(u.multiply(outnum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());//金额
			if (ToolUtil.isNotEmpty(batch)) {
				oodp.setDetailedBatchnumber(batch);//批次号
				oodp.setDetailedDate(strBuffer.toString());//生产日期
			}
			oodp.setDetailedRebubbles(bgr.getGoodsHeavybubble());//重泡货
			oodp.setDetailedLargeclass(bgr.getGoodsBigtype());//商品大类
			oodp.setDetailedGoodstype(bgr.getGoodsType());//商品类别
			oodp.setDetailedPutcondition(bgr.getGoodsCondition());//保管条件
			if(ToolUtil.isNotEmpty(ExcelItem.getUnit())) {
				oodp.setGoodsUnit(ExcelItem.getUnit());
			} else {
				oodp.setGoodsUnit(bgr.getGoodsUnit());//单位
			}
			oodp.setDetailedPacking(bgr.getGoodsPacking());//商品包装
			oodp.setGoodsSpecs(bgr.getGoodsSpecs());//规格
			oodp.setCreateTime(new Date());
			oodp.setCreateUser(user.getUserId());
			detailedList.add(oodp);
			oodp = new OutOrderDetailedParam();
		}
		if(detailedList.size()>0){
			this.saveBatchList(outorderList);
			if (transportList.size()>0) {
				orderTransportService.saveBatchList(transportList);
			}
			outOrderDetailedService.saveBatchList(detailedList);
		}
		data.setSuccess(true);
		if (dealWithParam.isNewCustomersflag()) {
			data.setCode(450);
			data.setMessage(dealWithParam.getNewCustomers().replaceAll("null", "")+"Please promptly maintain the route and correct the address for the new unit! To avoid affecting vehicle dispatching and driver delivery.");
		}
		return data;
	}

}
